I am supposed to get the product of the integer entered by user util a number that is less than 1 is entered, and print the product. But when the program does nothing after I enter the numbers. How can I fix this.
Here is the code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter integers: ");
int num = 1;
int product = 1;
while(input.hasNextInt() && num>=0){
num = input.nextInt(); product = product*num;
}
System.out.print("Product: "+product);
}
First, your test num>=0
is not a test for ending the loop when "a number that is less than 1 is entered", since 0
is less then 1 but won't end the loop.
Second, the test of num
is done after num
has been applied to product
. You don't want that.
So you need to test num
after getting it, but before applying it to product
. If less than 1, you want to end the loop, which you can do with a break
statement.
Also, it is generally bad style to put multiple statements on a single line.
System.out.println("Enter integers:");
int product = 1;
while (input.hasNextInt()) {
int num = input.nextInt();
if (num < 1)
break;
product *= num;
}
System.out.println("Product: " + product);
In your code, the while
loop keep running forever. So that's why it do not print anything.
Try this instead:
while(input.hasNextInt() && num>=0){
num = input.nextInt();
product = product*num;
System.out.print("Product: "+product);
}
EDIT: Try to enter the number less than 0
then your while
loop should terminate.
You could try something like this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter integers: ");
int num = 1;
int product = 1;
while(true)
{
try
{
num = input.nextInt();
if(num < 0)
{
break;
}
product = product * num;
} catch(InputMismatchException e)
{
System.out.println("Please enter a number.");
input.nextLine();
}
}
System.out.print("Product: "+product);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.