[英]I'm having trouble with looping in JAVA
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
I have solved my problem now. 我已经解决了我的问题。 But then I found a new problem! 但是后来我发现了一个新问题!
Enter Class Limit:
3
Enter Student Name:
Input Name
Enter Student Name:
Enter Student Name:
Here
Class Is Full
once I entered a space. 一旦我进入一个空间。 it is counted as two input in one line and skips the second line of entering and proceeding to the third. 它被视为一行中的两个输入,并跳过第二行进入并继续到第三行。 How do I make it accept space in one line and count it as one so that I can make it like this... 如何使它接受一行中的空间并将其计为一行,以便我可以像这样使它...
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
You aren't storing (or later displaying) the input. 您不会存储(或稍后显示)输入。 I think you wanted to do both. 我想你想两者都做。 Also, if you read an int
with nextInt()
you must then consume the nextLine()
. 另外,如果使用nextInt()
读取一个int
,则必须使用nextLine()
。 And you could use Arrays.toString(Object[])
to display your student names (so String
s). 您可以使用Arrays.toString(Object[])
来显示您的学生姓名 (即String
)。 Something like, 就像是,
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.