0
  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
  • Use `sc.nextLine().charAt(0)`. Also, look at this when you use `nextLine()` you will encounter the same issue - http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – Codebender Aug 23 '15 at 07:24
  • 1
    Unrelated, but is there a reason why you use a `char` as the iterator on the loop? – Spikatrix Aug 23 '15 at 07:26
  • I use char to read the names I input. – Joseph Lota Aug 23 '15 at 07:28
  • @JosephLota To iterate in a loop you don't need `char`, just with `int` you can do it. – Francisco Romero Aug 23 '15 at 07:32
  • I've change it. and yeah it works. my problem is solved now i used sc.nextLine().charAt(0) to accept the spaces and added a blank sc.nextLine() after the sc.nextInt() to fill the skipping of line – Joseph Lota Aug 23 '15 at 07:37

1 Answers1

2

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 Strings). 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));
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226