1
import java.util.Scanner;

class Student1{
    int a;
    String b;
    void get(int c, String d){
        a = c;
        b = d;
    }
    void show(){
        System.out.print("Id is " + a +"\n");
        System.out.print("Name is " + b);
    }
    public static void main(String args[]){
        Scanner one = new Scanner(System.in);
        System.out.print("Enter Id");
        int e = one.nextInt();
        System.out.print("Enter Your Name");
        String f = one.nextLine();
        Student1 s = new Student1();
        s.get(e ,f);
        s.show();
    }
}

when the program is executed it only asks for Id after that it shows result it never asks for Name

Cœur
  • 32,421
  • 21
  • 173
  • 232

3 Answers3

2

it gets complicated when you use nextInt() and nextLine() together. you can try this version which only uses nextLine();

public static void main(String args[]){
    Scanner one = new Scanner(System.in);
    System.out.print("Enter Id");
    String number =one.nextLine();
    int e = Integer.parseInt(number);
    System.out.print("Enter Your Name");
    String f = one.nextLine();
    Student1 s = new Student1();
    s.get(e ,f);
    s.show();
}

why nextInt() and nextline() produce some problems:

Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Community
  • 1
  • 1
nafas
  • 5,004
  • 1
  • 23
  • 47
1

You must be entering a newline after integer. For that that blank string is acting as input for one.nextLine(). To avoid that one way is to add one more one.nextLine() statement before String f = one.nextLine();

Soumitri Pattnaik
  • 2,592
  • 4
  • 21
  • 38
0

Use only nextLine() method and the change the below lines of your code too for efficient

  Student1 s = new Student1();
    s.get(e ,f);

create constructor for Student1 class

  Student1(int c, String d)
    {
      a = c;
      b = d;
    }

Inside main() method

Student1 s = new Student1(e,f);

You can initialize the variables at the time of creating object by using constructor.