I need to have this program promt the user if they would like to rerun but i get
ID: 3671832 • Letter: I
Question
I need to have this program promt the user if they would like to rerun but i get an error of Exception in thread "main" java.util.InputMismatchException
import java.util.Scanner;
public class PositiveNegative
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
{
boolean stop = false;
System.out.println ("Enter an integer, the input ends if it is 0: ");
do
{
double value;
int posCount = 0,negCount = 0;
double sum = 0.0;
value = input.nextDouble();
while (value != 0){
if (value > 0)
{
posCount++;
sum += value;
}
else if(value < 0)
{
negCount++;
sum += value;
}
value = input.nextDouble();
}
System.out.println ("The number of positives is: " + posCount);
System.out.println ("The number of negavtives is: " + negCount);
System.out.println ("The total is: " + sum);
System.out.println ("The average is: " + (sum/(negCount+posCount)));
System.out.println("Would you like to continue? (yes or no)");
String s = input.nextLine();
if(s.equals("no")) {
stop = true;
}
}
while (!stop);
}
}
}
Explanation / Answer
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
boolean stop = false;
System.out.println("Enter an integer, the input ends if it is 0: ");
do {
double value;
int posCount = 0, negCount = 0;
double sum = 0.0;
value = input.nextDouble();
while (value != 0) {
if (value > 0) {
posCount++;
sum += value;
} else if (value < 0) {
negCount++;
sum += value;
}
value = input.nextDouble();
}
System.out.println("The number of positives is: " + posCount);
System.out.println("The number of negavtives is: " + negCount);
System.out.println("The total is: " + sum);
System.out.println("The average is: "
+ (sum / (negCount + posCount)));
System.out.println("Would you like to continue? (yes or no)");
// replace nextLine() with next() method
// to read the word next() is enough
String s = input.next();
if (s.equals("no")) {
stop = true;
}
} while (!stop);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
OUTPUT:
Enter an integer, the input ends if it is 0:
5
2
8
-9
-5
0
The number of positives is: 3
The number of negavtives is: 2
The total is: 1.0
The average is: 0.2
Would you like to continue? (yes or no)
no
NOTE: please check the comment section
i wrote the code input.next() in the place of input.nextLine() at when reading
s(yes/no) value, here we are reading single word for that next() is enough,
no need nextLine()