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. 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));
}
}
答案 0 :(得分:0)
To get case insensitive comparison try
while (answer.equalsIgnoreCase ("y"));
For the highest and lowest create two new variables before the do
loop as
int lowest = Integer.MAX_VALUE;
int highest = Integer.MIN_VALUE;
In your loop do
lowest = Math.min (lowest, num);
highest = Math.min (higest, num);
答案 1 :(得分:-1)
Look at String.equalsIgnoreCase(String anotherString)
in Java documentation for lower and uppercase y
.
As for the highest/lowest number, create 2 variables and if they are null or lower/higher than current number, reassign them. 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.
答案 2 :(得分:-1)
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);
}