0

This is the my code and the problem is using array i am taking names and their marks input and want to print then serially but the name accepting part is not working it is taking number inputs but not the names

import java.util.Scanner;

public class ST_test 
{

    public static void main(String[] args) 
    { 
        int i;
        Scanner sc= new Scanner(System.in);
        String a[]= new String[5];
        int num[]= new int[5];
        for(i=0;i<5;i++)
        {
            
            System.out.println("position mrks"+i);
            num[i]=sc.nextInt();
            System.out.println("position name "+i);
            a[i]=sc.nextLine();

        }
        for(i=0;i<5;i++)
        {
            System.out.print(" "+a[i]+" ");
            System.out.print(" "+num[i]+" ");

       }

     }
}
InAlO
  • 1
  • 1
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Charlie Armstrong Feb 03 '21 at 19:30

1 Answers1

0

I used to encounter this error early on in my Java journey. The problem is with the Scanner class, probably a bug.

The solution that I used was to create 2 scanner class objects. One for the numeric values and the other for String values. Here is the modified code:-

import java.util.Scanner;

public class ST_test 
{

public static void main(String[] args) 
{ 
    int i;
    Scanner sc= new Scanner(System.in);
    Scanner sc1 = new Scanner(System.in); // new scanner object for Strings
    String a[]= new String[5];
    int num[]= new int[5];
    for(i=0;i<5;i++)
    {
        
        System.out.println("position mrks"+i);
        num[i]=sc.nextInt();
        System.out.println("position name "+i);
        a[i]=sc1.nextLine();

    }
    for(i=0;i<5;i++)
    {
        System.out.print(" "+a[i]+" ");
        System.out.print(" "+num[i]+" ");

   }

 }
 }

While this helps, it would be better to switch to BufferedReader and BufferedWriter class :)