Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Not sure where I've messed up?

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Not sure where I've messed up?

    I'm trying to do my final project for a class and I can't seem to get part of my code to work properly. The first loop only prompts for data the first time through; after that it skips straight into the nested loop. It's supposed to ask for 5 names and 5 scores for each name but I can only input 1 name.

    public class StudentAverageTestScore
    {
       public static void main(String[] asdf)
       {
          Scanner sc = new Scanner(System.in);
     
          String[] students = new String[5];
          int[][] scores = new int[5][5];
     
          for(int i=0; i<students.length; i++)
          {
             out.println("Enter the name of student " + (i+1));
             students[i] = sc.nextLine();
     
             for(int j=0; j<scores.length; j++)
             {
                out.println("Enter student's score for test " + (j+1));
                scores[i][j] = sc.nextInt();
                if(scores[i][j]<0 || scores[i][j]>100)
                {
                   out.println("Enter a valid test score.");
                   j--;
                }
             }
          }
       }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Not sure where I've messed up?

    sc.nextInt() leaves a linefeed in the input buffer which is then taken as input for the next sc.nextLine() call. Flush the buffer and throw it away with a sc.nextLine() call after the nested for loop.

Similar Threads

  1. [SOLVED] While loop messed up
    By jak15 in forum Loops & Control Statements
    Replies: 9
    Last Post: February 22nd, 2012, 09:57 PM
  2. JOption to JFrame HELP...messed my program up
    By scottgilliland2003 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: December 20th, 2011, 08:18 PM