如果我想在输入其他任何数字之前输入“ 0”来结束程序,我将使用(并将它们放置在何处?)
while (number == 0){
System.out.println("No numbers are entered except 0");
System.exit(0);}"
或者我会使用
if (number == 0){
System.out.println("No numbers are entered except 0");
System.exit(0);}"
我的程序如下:
import java.util.*;
public class Count2{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number, maxNum=0, count=0;
System.out.print("Enter a number (0 ends the input): ");
do {
number = input.nextInt();
if (number > maxNum){
count = 0;
maxNum = number;
}
if (number == maxNum){
count++;
}
}
while (number !=0);
System.out.println("The maximum numver is " +maxNum);
System.out.println("The count for the max number is " + count);
}
}}
我尝试将代码添加为在“ do”之前输入整数以及退出代码,但是当我这样做时,我的计数最终被弄乱了
答案 0 :(得分:2)
我只想进行while
的真实循环。请注意,count
首先应设置为1
int number=0, maxNum=0, count=0;
while (true) {
number = input.nextInt();
if (number == 0) {
break;
}
if (number > maxNum){
count = 1; // if greater than existing then set to one
maxNum = number;
}
else if (number == maxNum){
count++;
}
}
// print
if (count == 0){ // if a non-zero was entered then `count` will be `1`
System.out.println("No numbers are entered except 0");
}