-2

This code does not run correctly. I can't find out why the second time it runs the loop, it does not take a input for firstName variable it just prints "Enter First Name :".

import java.util.Scanner;

    public class Test {
        public static void main(String[]args){
          String[] firstName =  new String[30] ;
          String[] secondName = new String [30];
          int[] marksCourseWorkOne =  new int[30];
          int i;
          Scanner sc = new Scanner(System.in);
          for (i = 28; i < firstName.length; i++){
            System.out.print("\nEnter First Name : ");
            firstName[i] = sc.nextLine(); 
            System.out.print("\nEnter Second Name : ");
            secondName[i] = sc.nextLine();
            System.out.print("\nEnter Marks For Course Work One : ");
            marksCourseWorkOne[i] = sc.nextInt();
          }
     }
}
  • 10
    Oh, my. Where to begin. – Jim Buck Nov 17 '13 at 06:15
  • To begin with, you have code that needs to be within a method or constructor to work. Most importantly it looks like you're just guessing at what might work, throwing random code at the wall and hoping that some of it might stick, which is a guarantee of failure. You should consider reading a Java book or tutorial before trying to code. – Hovercraft Full Of Eels Nov 17 '13 at 06:17
  • @HovercraftFullOfEels Alot better than the first version of that comment. – Oxymoron Nov 17 '13 at 06:22

1 Answers1

4

First of all, don't use nextLine after nextInt, since the latter doesn't consume the \n char, and it'll be swallowed in the nextLine, making it skipping the real input you wanted to insert.

Second, if you were a compiler, what would you think i is? You will not know, because the programmer didn't tell you. You should write int i = 28 (Are you sure it should be 28 and not 0?).

Third, you don't have an entry point to the program, all of this should be inside the main method (Or any other method).

Solution:

  1. Read a basic tutorial.
  2. Define i.
  3. Add another nextLine right after nextInt to consume the \n.
  4. Add methods! (Related to 1).
Maroun
  • 94,125
  • 30
  • 188
  • 241