gpt4 book ai didi

java - 我在 JAVA 循环中遇到问题

转载 作者:行者123 更新时间:2023-12-02 04:25:57 25 4
gpt4 key购买 nike

  import java.util.Scanner;
public class Lab101{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);

System.out.println("Enter Class Limit:");
int x = sc.nextInt();

for (char i=1; i<=x; i++) {
System.out.println("Enter Student Name: ");
sc.next().charAt(0);
}

System.out.println("Class Is Full");}}

Enter Class Limit:
3
Enter Student Name:
Input
Enter Student Name:
Name
Enter Student Name:
Here
Class Is Full

现在我的问题已经解决了。但后来我发现了一个新问题!

Enter Class Limit:
3
Enter Student Name:
Input Name
Enter Student Name:
Enter Student Name:
Here
Class Is Full

一旦我进入一个空间。算作一行输入两次,跳过第二行输入进入第三行。我如何让它接受一行中的空格并将其计为一行,以便我可以使其像这样......

Enter Class Limit:
3
Enter Student Name:
Input Name Here
Enter Student Name:
Input Name Here
Enter Student Name:
Input Name Here
Class Is Full

最佳答案

您没有存储(或稍后显示)输入。我想你想两者都做。另外,如果您使用 nextInt() 读取 int,则必须使用 nextLine()。你可以使用 Arrays.toString(Object[])显示您的学生姓名(即字符串)。比如,

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

System.out.println("Enter Class Limit:");
int x = sc.nextInt();
sc.nextLine(); // <-- there's a newline.
String[] students = new String[x];
for (int i = 0; i < x; i++) {
System.out.printf("Enter Student Name %d: ", i + 1);
System.out.flush();
students[i] = sc.nextLine().trim();
}

System.out.println("Class Is Full");
System.out.println(Arrays.toString(students));
}

关于java - 我在 JAVA 循环中遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32164205/

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