0

I'm new in the community and I need help with Array 2d in Java Is a project for school this is my problem

I build Array 2D with static length and work but the same code with parameters not work.

First print the System.out.print("Insert Name");

after that not execute the statement matrix[i][0] = input.nextLine();

third print System.out.print("Insert Last Name");

now works but the index [0],[0] is empty

Example of print:

a

b b

c c

Thanks!!!

import java.util.*;

public class Students {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    System.out.println("Insert number of Students");

    int numStudents = input.nextInt();

    String[][] matrix = new String[numStudents][2];

    for (int i = 0; i < numStudents; i++) {

        System.out.print("Insert Name");

        matrix[i][0] = input.nextLine();                                                                            

        for (int j = 1; j < 2; j++) {

            System.out.print("Insert Last Name");

            matrix[i][j] = input.nextLine();

        }
    }

    for(int z=0; z<numStudents ;z++) {

        System.out.println();

        for(int h=0; h<2;h++) {

            System.out.printf(matrix[z][h]);
            System.out.printf(" ");
        }

    }

   }
  }
2

2 Answers 2

1

Use String value= input.next(); instead of input.nextLine(); or use an extra input.nextLine(); after input.nextInt(); i.e.

int numStudents = input.nextInt();
input.nextLine()

This happens because input.nextInt() just reads one integer and does not finishes the line.

Sign up to request clarification or add additional context in comments.

Comments

0

I think this should work for you. No need of a nested for loop to read last name.

   public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);

        System.out.println("Insert number of Students");

        int numStudents = input.nextInt();
        input.nextLine();
        String[][] matrix = new String[numStudents][2];

        for (int i = 0; i < numStudents; i++) {

            System.out.println("Insert Name");
            matrix[i][0] = input.nextLine();
            System.out.println("Insert Last Name");
            matrix[i][1] = input.nextLine();
        }

        for (int z = 0; z < numStudents; z++) {
            System.out.println();
            for (int h = 0; h < 2; h++) {
                System.out.print(matrix[z][h]);
                System.out.print(" ");
            }
            System.out.println();
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.