Reputation: 1
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
Upvotes: 0
Views: 95
Reputation: 201537
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()
. And you could use Arrays.toString(Object[])
to display your student names (so String
s). 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));
}
Upvotes: 2