[英]Finding highest value and lowercase/capitals in do-while loops
I have to write a program that asks the user to enter an integer value. 我必须编写一个程序,要求用户输入一个整数值。 After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even and find the averages of the numbers that the user entered. 在每个值之后,如果用户要继续执行程序,则用户必须以“ y”或“ n”作为响应,并且用户输入的每个数字都表示为奇数或偶数,并找出这些数字的平均值用户输入的内容。 I have completed all this, but I am confused on two things: 我已经完成了所有这些工作,但是我对两件事感到困惑:
Here is my code so far: 到目前为止,这是我的代码:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
double sum = 0;
int count = 0;
do {
int num;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
sum += num;
System.out.println(("Would you like to enter another value(y/n)?:"));
answer = scan.next();
count++;
} while (answer.equals("y"));
System.out.println("Average: " + (sum/count));
}
}
To get case insensitive comparison try 要获得不区分大小写的比较,请尝试
while (answer.equalsIgnoreCase ("y"));
For the highest and lowest create two new variables before the do
loop as 对于最高和最低值,请在do
循环之前创建两个新变量,如下所示:
int lowest = Integer.MAX_VALUE;
int highest = Integer.MIN_VALUE;
In your loop do 在你的循环中
lowest = Math.min (lowest, num);
highest = Math.min (higest, num);
Look at String.equalsIgnoreCase(String anotherString)
in Java documentation for lower and uppercase y
. 在Java文档中查看String.equalsIgnoreCase(String anotherString)
中的小写和大写y
。
As for the highest/lowest number, create 2 variables and if they are null or lower/higher than current number, reassign them. 对于最高/最低编号,请创建2个变量,如果它们为空或低于/高于当前编号,请重新分配它们。 By the end of the program, you will have appropriate value. 在程序结束时,您将具有适当的价值。
This is too simple to provide you the code, so, the explanation above is enough so far. 这太简单了,无法为您提供代码,因此,到目前为止,上面的解释就足够了。
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
double sum = 0;
int count = 0;
**int max = 0;**
do {
int num;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
sum += num;
System.out.println(("Would you like to enter another value(y/n)?:"));
**max = (num > max) ? num : max ;**
answer = scan.next();
count++;
} while (answer.equals("y"));
System.out.println("Average: " + (sum/count));
System.out.println("Highest : " + max);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.