Problems with Scanner - Java

那年仲夏 提交于 2019-12-04 11:56:43

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();

}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!