簡體   English   中英

為什么我的代碼會引發NoSuchElementException?

[英]Why does my code throw a NoSuchElementException?

我學校作業的Java程序給我一個錯誤:

Welcome to Surinam Airlines - We may get you there!

We have 6 seats available for flight JAVA123.

How many seats do you want to book? 3

Enter passenger #1's name: Taylor Swift
Enter passenger #1's food option
(V = vegetarian, N = no preference, H = Halal): V
Enter passenger #1's class (1 = first, 2 = business, 3 = economy): 1
Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.util.Scanner.nextLine(Unknown source)
        at Passenger.enterPassenger(Passenger.java:64)
        at RunAirLine.main(RunAirLine.java:23)

盡管我不太清楚為什么,但似乎與未實例化該對象有關。 有人知道怎么了嗎?

import java.util.*;

public class RunAirLine {

  private static Passenger seatArray[][] = new Passenger[2][3]; // declares new
                                                                // array of
                                                                // Passengers
  static Scanner kb = new Scanner(System.in);

  public static void main(String[] args) {
    System.out.println("Welcome to Surinam Airlines – We may get you there!");
    System.out.println();

    int seats = 6; // available seats
    while (seats > 0) {
      System.out.println("We have " + seats
          + " seats available for flight JAVA123.");
      System.out.println();
      System.out.print("How many seats do you want to book? ");
      int n = kb.nextInt();
      System.out.println();

      for (int i = 0; i < n; i++) {
        int x = emptySeat()[0];
        int y = emptySeat()[1];
        // retrieves info from emptySeat() function
        seatArray[x][y] = new Passenger();
        seatArray[x][y].enterPassenger(7 - seats); // gives the method the nth
                                                   // passenger number
        seats--; // takes away 1 from the available seats
      }
      System.out.println();
    }
    System.out.println("No seats available.");
    System.out.println();
    System.out.println("Flight manifest:");
    System.out.println();
    for (int y = 0; y < 3; y++) { // prints out the list of flyers
      for (int x = 0; x < 2; x++) {
        System.out.println(seatArray[x][y].getSeat() + " "
            + seatArray[x][y].printPassengerCode());
      }
    }
    kb.close();
  }

  public static int[] emptySeat() {
    for (int y = 0; y < 3; y++) {// finds the next empty seat
      for (int x = 0; x < 2; x++) {
        if (seatArray[x][y] == null || seatArray[x][y].getSeat().equals("")) {
          // if the spot hasn't been declared yet or is empty
          return new int[] { x, y };
        }
      }
    }
    return null; // if none found then return null
  }
}

Passenger.java

import java.util.*;

public class Passenger {
  private String name;
  private String seat;
  private char foodOption;
  private int seatClass;

  // reduces some redundancy
  private String classStr;
  private String prefStr;

  public Passenger() { // constructors
    name = "";
    seat = "";
    foodOption = ' ';
    seatClass = -1;
  }

  public Passenger(String n, String s, char f, int sc) { // assigns values
                                                         // according to input
    name = n;
    seat = s;
    foodOption = f;
    seatClass = sc;
  }

  // get and set methods
  public void setName(String n) {
    name = n;
  }

  public void setSeat(String s) {
    seat = s;
  }

  public void setFoodOption(char f) {
    foodOption = f;
  }

  public void setSeatClass(int sc) {
    seatClass = sc;
  }

  public String getName() {
    return name;
  }

  public String getSeat() {
    return seat;
  }

  public char getFoodOption() {
    return foodOption;
  }

  public int getSeatClass() {
    return seatClass;
  }

  // end of get and set methods

  public void enterPassenger(int i) {
    Scanner kb = new Scanner(System.in);
    // asks the important questions
    System.out.print("Enter passenger #" + i + "’s name: ");
    name = kb.nextLine();
    System.out.println("Enter passenger #" + i + "’s food option ");
    System.out.print("(V = vegetarian, N = no preference, H = Halal): ");
    foodOption = kb.nextLine().toUpperCase().charAt(0);
    System.out.print("Enter passenger #" + i
        + "’s class (1 = first, 2 = business, 3 = economy): ");
    seatClass = kb.nextInt();

    System.out.println();
    char seatChar = 'A'; // calculates the seat number
    if (i % 2 == 0)
      seatChar = 'B';
    seat = Integer.toString(i / 2 + i % 2) + seatChar;

    classStr = "Economy Class"; // transfers the class choice int into string
    switch (seatClass) {
    case 1:
      classStr = "First Class";
      break;
    case 2:
      classStr = "Business Class";
      break;
    }

    prefStr = "No preference"; // transfers the preference char into string
    switch (foodOption) {
    case 'V':
      prefStr = "Vegetarian";
      break;
    case 'H':
      prefStr = "Halal";
      break;
    }

    System.out.println("Done – Seat " + seat + " booked");
    System.out
        .println("-------------------------------------------------------------------");
    System.out.println(name + "(" + classStr + " - Seat " + seat + ") - "
        + prefStr);
    System.out
        .println("-------------------------------------------------------------------");
    kb.close();
  }

  public void printTicketStub() {
    char initial = name.split(" ")[0].toUpperCase().charAt(0); // splits name
                                                               // into first
                                                               // name and
                                                               // second name
    System.out.println(initial + ". " + name.split(" ")[1] + "(" + classStr
        + " - Seat " + seat + ") - " + prefStr);
  }

  public String printPassengerCode() { // forms the code as required
    return seatClass + name.toUpperCase().substring(name.length() - 4)
        + foodOption;
  }
}

您有兩個問題:

  1. 您為System.in創建了一個Scanner兩次。 您只能執行一次。 我已注釋掉您在Passenger.java創建的那個,並將引用更改為RunAirLine.java中的RunAirLine.java

     public void enterPassenger(int i) { // Scanner kb = new Scanner(System.in); // asks the important questions System.out.print("Enter passenger #" + i + "'s name: "); name = RunAirLine.kb.nextLine(); System.out.println("Enter passenger #" + i + "'s food option "); System.out.print("(V = vegetarian, N = no preference, H = Halal): "); foodOption = RunAirLine.kb.nextLine().toUpperCase().charAt(0); System.out.print("Enter passenger #" + i + "'s class (1 = first, 2 = business, 3 = economy): "); seatClass = RunAirLine.kb.nextInt(); RunAirLine.kb.nextLine(); 
  2. 每次您執行nextInt() ,它都不會使Scanner的讀數出現新的一行,這會弄亂東西。 如果要使nextInt()在其自己的行上,則應拋出一個虛擬RunAirLine.kb.nextLine(); nextInt()調用之后。 這需要做兩次,一次在我上面確定的代碼中,一次在您的RunAirLine.class

     System.out.print("How many seats do you want to book? "); int n = kb.nextInt(); kb.nextLine(); System.out.println(); 

進一步閱讀為什么不應該使用多個Scanner 的tl; dr是關閉System.in永遠關閉流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM