编写一个读取整数的程序,查找其中最大的整数,并计算其出现次数。假设输入以数字0结尾。假设您输入3 5 2 5 5 5 0;程序发现最大值为5,5的出现次数为4。
设计程序,允许用户重新运行 在同一次运行中使用不同输入的程序。
public void findLargestInteger(){
//create Scanner object
Scanner input = new Scanner(System.in);
int x;
do {
//prompt user input
System.out.print("Enter an integer, the input ends if it is 0:");
//declare variables
int n, countNeg = 0, countPos = 0;
float sum = 0;
//calculate how many positive and negative values, total, and average
while ((n = input.nextInt()) != 0) {
sum = sum + n;
if (n > 0) {
countPos++;
}
else if (n < 0) {
countNeg++;
}
}
//display results
if (countPos + countNeg == 0) {
System.out.println("No numbers are entered except 0");
System.exit(0);
}
System.out.println("The number of positives is " + countPos);
System.out.println("The number of negatives is " + countNeg);
System.out.println("The total is " + sum);
System.out.println("The average is " + (sum / (countPos + countNeg)));
}while ((x = input.nextInt()) != 0);
}
如何在最后提示正确显示并保留它 运行?
输出:
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0 The average is 3.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0
The average is 3.0
答案 0 :(得分:1)
如果您真的想继续重复计划,可以将while((x = input.nextInt()) != 0);
更改为while(true);
。
这是一个无限循环,虽然这不是一个好方法。
因此,您可以编写类似
的内容,而不是寻找下一个整数并与0进行比较System.out.print("Do you want to quit? (y/n): ");
在你的循环结束时(就在while((x = input.nextInt()) != 0)
行之前)。
然后不检查0但是y
。至少那时你没有让程序等待用户输入内容而不知道发生了什么。
编辑:或者你可以使用一个计数器,如果你想在它终止之前运行它两次或三次;)
答案 1 :(得分:0)
您是否尝试过在while循环中调用函数?
public void findLargestInteger() {
// Your code
}
public static void main(String[] args) {
do {
findLargestInteger();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Would you like to continue? (0/1) ");
int n = reader.nextInt();
} while(n == 1);
}