在这个程序中,我需要用户在另一个数组类中输入yes / no。但是字符串输入不起作用。我用一个整数尝试了它,但它没有用字符串。
package airliner.boarding.system;
import java.util.Scanner;
公共类BoardPlane {private boolean firstClass[];
private boolean economyClass[];
private static Scanner input ;
public BoardPlane(){
firstClass = new boolean[5];
economyClass = new boolean[5];
input = new Scanner(System.in);
}
public void setSeat(int seatClass){
if(seatClass == 1){
fillFirstClass();
}else if(seatClass == 2){
fillEconomyClass();
}
}
private void fillEconomyClass(){
for(int counter = 0; counter < economyClass.length; counter++){
if(economyClass[counter] == false){
economyClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the economy class");
break;
}else if(counter == 4){
System.out.println("Economy class is filled. is it okay to place you in first class? YES/NO: ");
String choice = input.nextLine();
choice = choice.toUpperCase();
if(choice.equals("YES")){
switchSeats(2);
}else{
System.out.println("Next flight leaves in three hours.");
}
}
}
}
private void fillFirstClass(){
for(int counter = 0; counter < firstClass.length; counter++){
if(firstClass[counter] == false){
firstClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the first class");
break;
}else if(counter == 4 ){
System.out.println("First class is filled. is it okay to place you in economy class? YES/NO:");
String choice = input.nextLine();
choice = choice.toUpperCase();
if(choice.equals("YES")){
switchSeats(1);
}else{
System.out.println("Next flight leaves in three hours.");
}
}
}
}
private void switchSeats(int i){
if(i == 1){
for(int counter = 0; counter < economyClass.length; counter++){
if(economyClass[counter] == false){
economyClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the economy class");
break;
}else if(counter == 4){
System.out.println("Economy class is filled");
}
}
}else if(i == 2){
for(int counter = 0; counter < firstClass.length; counter++){
if(firstClass[counter] == false){
firstClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the first class");
break;
}else if(counter == 4){
System.out.println("First class is filled");
}
}
}
}
public static void main(String [] args){
BoardPlane plane = new BoardPlane();
for(int i = 0; i <= 10; i++){
System.out.println("Enter 1 for first class and 2 for economy class: ");
int userInput = input.nextInt();
plane.setSeat(userInput);
}
}
}
答案 0 :(得分:1)
当你致电nextInt()
时,它只会读取数字,而不会读取该行的其余部分,而不是您输入的新行。
这意味着如果您稍后致电nextLine()
,它会读取该号码之后的内容,即很可能没有。
一个简单的解决方法是忽略数字后面的其余部分。
int userInput = input.nextInt();
input.nextLine(); // ignore the rest of the line.
答案 1 :(得分:0)
我有同样的问题,当你使用扫描仪,并把消息与System.out.println(),newLine无法正常工作。我不知道为什么?!当您在控制台中输出消息后输入= new Scanner(System.in)时,它的工作正常。
但是你可以制作一个方法来提供用户输入,并且在这个方法中制作一个像这样的重新扫描器:
publis static String getUserInput(String message){
的System.out.println(消息);
input = new Scanner(System.in);
返回input.nextLine();
}