gpt4 book ai didi

java - 在控制台显示输出时遇到问题

转载 作者:行者123 更新时间:2023-12-01 23:32:03 25 4
gpt4 key购买 nike

我试图将输入存储在数组 Interior_games 中并将其输出到屏幕,但是当我执行代码时,它在接受 1 个值后突然结束执行。

package games;
import java.util.*;
import java.lang.*;
class Indoor{
String name;
Indoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Outdoor{
String name;
Outdoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
for(int i=0;i<size;i++){
name = sc.next();
indoor_games[i] = new Indoor(name);
}
for(int i=0;i<size;i++)
indoor_games[i].display();
}
}

更新了代码并添加了 nextLine 但仍然存在相同的问题:

class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
sc.nextLine(); //To consume the newline character
Indoor[] indoor_games = new Indoor[size];
for(int i = 0 ; i < size ; i++){
name = sc.nextLine();
indoor_games[i] = new Indoor(name);
}
for(int i = 0 ; i < size; i++)
indoor_games[i].display();
}
}

输出(命令行)

D:\Docs Dump\School stuff\JAVA\Java slips>java games.Slip20

输入室内游戏的玩家人数:

3

尼拉吉

D:\Docs Dump\School stuff\JAVA\Java slips>

如您所见,扫描仪仅接受“Neeraj”,程序结束

执行。

最佳答案

只需将 sc.next() 替换为 sc.nextLine()

关于java - 在控制台显示输出时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58286000/

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