所以我的家庭作业问题是提示用户输入一系列整数并找出这些整数的最大值和最小值。使用循环和 -99 来中断循环。下面是我的代码,但我的问题是有更短的方法吗?请随时发表评论,感谢您花时间阅读本文。
Scanner input=new Scanner(System.in);
int num1,num2,max,min;
System.out.print("enter a number: ");
num1=input.nextInt();
System.out.print("enter another number: ");
num2=input.nextInt();
max=Math.max(num1,num2);
min=Math.min(num1,num2);
while (num2!=-99){
System.out.print("enter a number or -99 to stop: ");
num2=input.nextInt();
if(num2!=-99){
max=Math.max(max,num2);
min=Math.min(min,num2);
}
}
System.out.println("largest is: "+max);
System.out.println("Smallest is: "+min);
最佳答案
你检查了两次 num2 != -99
的条件,记住编程的第一条规则,不要重复自己
在询问下一个输入之前,您可以通过检查最小值和最大值来节省一些行。这样你就不需要在 while 循环中检查 num2 != -99
关于java - 使用 while 循环让用户输入多个 int 并找到最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46209659/