简体   繁体   中英

Infinite printing when trying to use a loop

new to programming.

I have a class in java and i'm trying to write this program but it's printing none-stop and it's even bugging my browser! (Im using an online ide)

my instructions: Q: how much do you love me? Below 10 : wrong answer equal to 10 and more = good answer

I know how to do it but I dont want the program to stop every time i write an answer. I want the program to keep running until i have a 10 +. So i can always input until it's 10+ out of 10.

this is my lines :

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    System.out.println ("how much do you love me out of 10");
    int num1 = input.nextInt();

    while (true) 
    if (num1 <= 9) {
    System.out.println("Wrong answer");
    }
       else {
       System.out.println ("Good answer");
       }
 }
}

This should work:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner (System.in);
        System.out.println ("Out of 10, how much do you love me?");
        int input = 0
        while (input <= 9) {
            input = scanner.nextInt();
            if (input <= 9) {
                System.out.println("Wrong answer");
            } else {
                System.out.println("Good answer");
            }
        }
    }
}

Explanation: It loops until input is less not less than or equal to 9 ( while (input <= 9) ). Each time through the loop, it gets input and acts on it.

Hope this helps!

First off, you need to move the int num1 = input.nextInt(); statement inside your while loop, this will allow for a new input every time the while loop loops (iterates).

Second, if you are looking to run the program until num1 >= 10 , then you could implement it in two ways.

while(num1 < 10) {
    num1 = input.nextInt();

    if(num1 >= 10) {
        System.out.println("Good answer");
    } else {
        System.out.println("Wrong answer");
    }
}

or using the keyword break ,

while(true) {
    num1 = input.nextInt();

    if(num1 >= 10) {
        System.out.println("Good answer");
        break;
    } else {
        System.out.println("Wrong answer");
    }
}

break simply escapes the loop it resides in when called

Hoped this helped

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM