Problems with Scanner - Java

后端 未结 2 973
遥遥无期
遥遥无期 2020-12-18 08:32

I\'m trying to have the option of reading a string with multiple words, ie. Los Angeles or New York City. Using scanner.next() for \"Departure\" and \"Arrival\" would only r

相关标签:
2条回答
  • 2020-12-18 08:51

    Your problem is that next() does not read the carriage return and it gets automatically read by your next next() or nextLine(). Use nextLine() all time and convert input to integer:

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\nEnter flight number: ");
        int flightNumber = Integer.valueOf(scanner.nextLine());
        System.out.print("\nEnter departing city: ");
        String departingCity = scanner.nextLine();
        System.out.print("\nEnter arrival city: ");
        String arrivalCity = scanner.nextLine();
    
    }
    
    0 讨论(0)
  • 2020-12-18 09:13

    Integer.parseInt(scanner.nextLine()) would also work--it returns an int, while Integer.valueOf(scanner.nextLine()) returns an Integer.

    As an alternative to @Edwin Dalorzo's suggestion, you can call nextInt() to grab the next token from the input stream and try to convert it to an int. This method will throw an InputMismatchException if conversion to an int was unsuccessful. Otherwise, it will grab only the int value entered. Calling nextLine(), will then grab anything else that was entered in the line after the int. In addition, nextLine() will consume the newline character added when the user pressed "enter" to submit the input (it will advance past it and discard it).

    If you want to be sure that the user didn't enter anything except an int before pressing "Enter," call nextInt() first and then make sure the value of nextLine() is empty. If you don't care about anything entered in the line after the int, you can ignore what nextLine() returns but should still call that method to consume the newline character.

    Search StackOverflow for "java scanner next" or "java scanner nextLine" to find threads on this subject.

    0 讨论(0)
提交回复
热议问题