Reputation: 21
I am trying to ask the user if they want to continue inputting numbers to add to a total value
int total=0;
char letter='y';
while (letter == 'y');
{
Scanner userInput = new Scanner (System.in);
System.out.println("Input your number");
int number = userInput.nextInt();
total=number+total;
Scanner userInput1 = new Scanner (System.in);
System.out.println("Would you like to continue? Input y/n");
char letter = userInput1.next().charAt(0); //**This is where there is an error**
}
System.out.println("The total of all the numbers inputted is "+total);
}
}
Upvotes: 1
Views: 59
Reputation: 8214
;
on line 5 (the while
line).Scanner
only once, outside the loop.letter = ***
instead of char letter = ***
. You already declared the variable letter
.nextInt
line in case user typed a non-number.Possible improvement:
int total=0;
char letter='y';
Scanner userInput = new Scanner(System.in);
while(letter == 'y')
{
System.out.println("Input your number");
int number = userInput.nextInt();
total += number;
System.out.println("Woud you like to continue? Input y/n");
letter = userInput.next().charAt(0);
}
Upvotes: 2
Reputation: 26926
Simply remove char
, because letter
was already defined. Instead of
char letter = userInput1.next().charAt(0);
write
// char removed
letter = userInput1.next().charAt(0);
And also as Pemap said remove the ;
after the while
Basically your code should be similar to the following
while (letter == 'y') {
Scanner userInput = new Scanner (System.in);
System.out.println("Input your number");
int number = userInput.nextInt();
total = number + total;
Scanner userInput1 = new Scanner(System.in);
System.out.println("Would you like to continue? Input y/n");
letter = userInput1.next().charAt(0);
}
Upvotes: 1
Reputation: 6265
2 problems. 1st) you have a ; in a while statement line. 2nd) you have already declared letter variable. No need to declare it again after asking for input the 2nd time. Hope it helps.
int total=0;
char letter='y';
while (letter == 'y')
{
Scanner userInput = new Scanner (System.in);
System.out.println("Input your number");
int number = userInput.nextInt();
total=number+total;
Scanner userInput1 = new Scanner (System.in);
System.out.println("Would you like to continue? Input y/n");
letter = userInput1.next().charAt(0); //**This is where there is an error**
}
System.out.println("The total of all the numbers inputted is "+total);
}
}
Upvotes: 1