gpt4 book ai didi

java - 程序不提示输入字符串,但提示其他数据类型

转载 作者:行者123 更新时间:2023-12-01 11:57:11 24 4
gpt4 key购买 nike

在这个程序中,我需要用户输入是/否以在另一个数组类中设置。但是字符串输入不起作用。我用整数尝试过,它可以工作,但不能用字符串。

包airliner.boarding.system;

导入java.util.Scanner;

公共(public)类 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);
}
}

}

最佳答案

当您调用 nextInt() 时,它只会读取数字,不会读取该行的其余部分,也不会读取您键入的新行。

这意味着如果您稍后调用nextLine(),它将读取该数字后面的内容,即很可能什么也没有。

一个简单的解决方法是忽略数字后面的行的其余部分。

int userInput = input.nextInt();
input.nextLine(); // ignore the rest of the line.

关于java - 程序不提示输入字符串,但提示其他数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366730/

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