Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4.
Design the program such it allows the user to re-run the program with a different inputs in the same run.
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
最佳答案
你可以将 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
。至少这样您就不会让程序在不知道发生了什么的情况下等待用户输入内容。
编辑:或者如果你想在它终止之前运行它两次或三次,你可以只使用一个计数器;)
关于java - 在同一次运行中重新运行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807486/