简体   繁体   中英

Why can't I break my while loop by press 'enter'

Anyone please help me with the break of the while loop, I just want to end the program when user types nothing in, but why cannot it work? Please do help, thanks a lot.

import java.util.Random;
import java.util.Scanner;
import java.lang.Math;

public class Determining_Pi_Experiment {
    public static void main(String[] args) {
        while (true) {
            System.out.println("Press 'enter' to exit, or type an integer number indicating for how many times you " +
                    "want the experiment run: ");
            Scanner input = new Scanner(System.in);
            if(!input.equals(null)) {
                if(input.hasNextInt()) {

                    System.out.println("Processing...");
                    Random rand = new Random();
                    int ExperimentTimes = input.nextInt();
                    double count_success = 0;
                    double Pi = 0;

                    for (int i = 0; i < ExperimentTimes; ++i) {

                        double x = rand.nextDouble();
                        double y = rand.nextDouble();

                        double distance = Math.pow(Math.pow((x - 0.5), 2) + Math.pow((y - 0.5), 2), 0.5);

                        if (distance <= 0.5) {
                            ++count_success;
                        }
                    }
                    Pi = (count_success / ExperimentTimes) * 4;
                    System.out.println("Pi is approximately equal to: " + Pi);
                }
                else {
                    System.out.println("Invalid input.");
                }
            }
            else if(input.equals(null)) {
                System.exit(0);
            }
        }
    }
}

I can see many mistakes in your code, I'll walk you through them.

1) Overly complex, overly verbose, checks that aren't needed 2) Missuse of the #equals method 3) Not following standard naming conventions 4) General misunderstanding of how to structure an input-reading loop

To expand on them:

1) Try to simplify your code, remove the while true loop and the else clause (see point 4), declare variables only once, outside, remove reduntant parentheses. Also, the distance can be computed as Math.hypot(x1-x2, y1-y2) (See here )

2) Notice that the equals method should be used to check if an object is equal to another object. If it were to return true in your example, that would mean that the scanner itself is null (not what it's reading), so the check couldn't work because a NullPointerException would be thrown (calling a method on the null scanner). To check if a Scanner (or any object) is null, you instead want to do anyObject == null . Notice that this has nothing to do with the Scanner input (see point 4).

3) Please correctly name the variables ( see here ).

4) If you want to keep reading the user input up to the point where no more input is available, you should use Scanner#hasNext . If you instead want to end when an empty string is entered, you should indeed check that the string is empty. This has nothing to do with the scanner being null. someString.isEmpty() will do the job for you.

Pseudo loop:

while(scanner.hasNextLine() && !((line = scanner.nextLine()).isEmpty()))
 //do something with the input, stored in the line String

//Exits when enter is pressed (or EOF)

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