gpt4 book ai didi

java - 当用户在Java中输入并打印时,for循环跳过索引0

转载 作者:行者123 更新时间:2023-12-02 09:02:59 27 4
gpt4 key购买 nike

例如,我输入的人数为 3 名学生。它在打印时也会跳过控制台中的索引 0。

Please refer to this image, I have a sample size of 3 students and its output.

我一点也不知道为什么它会跳过索引 0?感谢您的帮助!

import java.util.Arrays;
import java.util.Scanner;

class string{

public static void main(String [] args){
Scanner console = new Scanner(System.in);

System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
String [] arrName = new String[studentSize];

for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}

System.out.print(Arrays.toString(arrName));

//Closing Braces for Class and Main
}
}

最佳答案

问题出在 console.nextInt() 上,该函数仅读取 int 值。因此在循环内的代码中 console.nextLine() 第一次跳过获取输入。只需将 console.nextLine() 放在 console.nextInt() 之后你可以解决问题。

public static void main(String [] args){
Scanner console = new Scanner(System.in);

System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
console.nextLine();
String [] arrName = new String[studentSize];

for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}

System.out.print(Arrays.toString(arrName));

//Closing Braces for Class and Main

}

关于java - 当用户在Java中输入并打印时,for循环跳过索引0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60032989/

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