kim kim - 11 days ago 5
Java Question

How to correct my sentinel value?

My code is supposed to ask for a name, ask for a number between one and ten, print the numbers from 1 to the number the user entered except every third number should
be the user's name that was entered at the beginning of the program, print the even numbers, continually ask the user for numbers until the user enters the sentinel, and then print the total of the numbers entered. (I know, that's a lot.) My code is running fine, the only problem I am having is with the last part. Even when the user enters the sentinel, which in this case is -1, the program still asks for another entry. Did I do something wrong when declaring the variable or can someone explain how to fix my problem? Here is my code.
import

java.util.Scanner;

/**
*
* @author Home
*/
public class NewClass1 {
public static void main(String[] args) {

int number;

Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();

System.out.print( "Please enter a number between 1 and 10: ");
number = scan.nextInt();

//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print( "No, between 1 and 10: ");
number = scan.nextInt();
}

for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");

final int SENTINEL = -1;
int inputNumber;
int total = 0;

System.out.println(" Enter a number or -1 to finish. " );
inputNumber = scan.nextInt();

while ( inputNumber != SENTINEL )
{
total += number;

System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println( "The total is " + total);
}
}

Answer

Solution:

You get input from user and saving that input in varible called number but you are checking your while against inputNumber.

   while ( inputNumber != SENTINEL )
   {
       total += number;
       System.out.print("Enter the next number or '-1' to finish. ");
       inputNumber = scan.nextInt();  <<< not number should be inputNumber
   }
Comments