gpt4 book ai didi

java - 线程 "main"java.util.NoSuchElementException : No line found 中出现异常

转载 作者:行者123 更新时间:2023-12-02 07:17:36 24 4
gpt4 key购买 nike

我正在尝试获取用户输入,在第二个输入值之后出现此错误:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at Reservations.start(Reservations.java:50) at Reservations.main(Reservations.java:29)

import java.util.Scanner; // Needed to read user input

public class Reservations {

// Boolean array for seating [false = available, true = taken]
static boolean[][] seats;

// Main method
public static void main(String[] args) {

// Initiates all array values to be false (available)
seats = new boolean[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
seats[i][j] = false;
}

// Welcome message
System.out.println("-------------------------");
System.out.println("Welcome to NSCC AirLines.");
System.out.println("-------------------------\n");

// Starts program
start();
}
}

public static void start() {

// Scanner needed to read users input
Scanner sc = new Scanner(System.in);

// Variables for user input
String requestedSection;
String requestedSeat;

// Counters for seating array
int countSection = 0;
int countSeat = 0;

// Prompts the user to select their choice of section
System.out.print("Please type 1 for First Class or 2 for Economy: ");

// Section preference
requestedSection = sc.nextLine();

switch (requestedSection) {
case "1":
// User selects first class
System.out.println(">>> You have selected First Class. \n");
break;

case "2":
// User selects economy
System.out.println(">>> You have selected Economy. \n");
break;

default:
// User has not selected a valid class
System.out
.println(">>> You have not selected a valid class. Please try again. \n");
start();
break;
}

// Prompts the user to select their choice of seat
System.out.print("Please type 1 for window and 2 for aisle: ");

// Seat preference
requestedSeat = sc.nextLine();

switch (requestedSeat) {
case "1":
// User selects first class
System.out.println(">>> You have selected a window seat. \n");
break;

case "2":
// User selects economy
System.out.println(">>> You have selected an aisle seat. \n");
break;

default:
// User has not selected a valid class
System.out.println(">>> You have not selected a valid seat. Please try again. \n");
start();
break;
}

// Closes Scanner
sc.close();
}
}

最佳答案

readLine()的API文档方法如下

Throws:
NoSuchElementException - if no line was found

您应该处理此异常或仅使用 hasNextLine()方法来避免异常。

while(sc.hasNextLine()){
requestedSeat = sc.nextLine();
}

关于java - 线程 "main"java.util.NoSuchElementException : No line found 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14741592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com