我试图获得循环运行次数的输出,由用户决定。我使用while()
,但我不确定循环结束后如何输出循环数。
这是我的代码:
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
int number1 = input.nextInt();
System.out.println("You Chose Number " + number1);
while (number1 != 1) {
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
}
}
请帮我谢谢!!
您只需要一个额外的变量,该变量在每次循环发生时递增。然后在循环之后,您可以使用该变量来显示循环的次数。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
int number1 = input.nextInt();
int loopcount = 0;
System.out.println("You Chose Number " + number1);
while (number1 != 1){
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
loopcount += 1;
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
System.out.println("Looped " + loopcount + " times";
}
顺便说一句,您还可以通过消除"输入"之前的输入请求来优化功能;while(("环它是重复的、冗余的代码,不需要存在。
例如:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number1 = 0;
int loopcount = -1;
while (number1 != 1) {
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
loopcount += 1;
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
System.out.println("Looped " + loopcount + " times";
}
如果只需要计算循环次数,那么取一个int变量就足够了,但如果您想记录所选数字则取一个List,该List可以动态存储所选数字,其长度将为循环次数。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice = 0;
int count=0;
List<Integer> numbers = new ArrayList(); // if chosen num is needed
do{
System.out.print("Choose a number between 2 and 10, choose 1 to end it :");
choice = scanner.nextInt();
if(choice !=1 ) {
count++;
numbers.add(choice); // if chosen num is needed
}
}while (choice != 1);
System.out.println("Loop counts " + count);
System.out.println("Loop counts " + numbers.size() + " times and numbers are "+numbers);
}