習題--陣列中的迴圈
阿新 • • 發佈:2018-12-25
有n個人圍成一圈,順序排號。從第一個人開始報數(從1到3報數),
凡是報到3的人退出圈子,問最後留下來的是原來第幾號的那位。
import java.util.Arrays; import java.util.Scanner; public class Round { public static void main(String[] args) { // TODO Auto-generated method stub //用陣列儲存資料 // int[] person={1,2,0,4,5,6,7}; // {1,2,0,4,5,6,7}3 // {1,2,0,4,5,0,7}6 // {1,0,0,4,5,0,7}2 // {1,0,0,4,5,0,0}7 // {1,0,0,4,0,0,0}5 // {0,0,0,4,0,0,0}1 System.out.print("請輸入人數"); Scanner sc=new Scanner(System.in); int count=sc.nextInt(); int[] person=new int[count]; for(int i=0;i<count;i++) { person[i]=i+1; } int num=0; int length=count; for(int i=0;i<count;i++) { //如果num是3, if(person[i]!=0) { num++; } if(num==3) { //並且當前數字不是0,就把當前數字變成0 if(person[i]!=0) { person[i]=0; num=0; length--; // System.out.println(Arrays.toString(person)); } else { continue; } } if(i==count-1) { i=-1; } if(length==1) { for(int j:person) { if(j!=0) { System.out.println("最後剩下的是"+j); } } return; } } } }