Wednesday 22 June 2016

java - .nextLine() method does not take subsequent String inputs




I have a program that asks the user for an input of numbers and characters. For this I am using a Scanner class. But when I take two subsequent string inputs, the console just moves and asks the user to input the second string. The user is unable to input the first string. I have attached my code below to be more specific.




import java.util.Scanner;

class XYZ {

public static void main(String args[]) {
int x, y, z, b, c;
String p, q;
Scanner sc = new Scanner(System.in);


System.out.println("Enter a number");
b = sc.nextInt();

System.out.println("Enter a new number");
c = sc.nextInt();

System.out.println("Enter a String");
p = sc.nextLine();

System.out.println("Enter a new String");

q = sc.nextLine();

System.out.println("Enter a number");
x = sc.nextInt();

System.out.println("Enter 2nd number");
y = sc.nextInt();

System.out.println("Enter 3rd number");
z = sc.nextInt();


ABC a = new ABC();

a.PQR(b, c);
a.PQR(p, q);
a.PQR(x, y, z);
}
}

class ABC {


void PQR(int a, int b) {
int res = a + b;
System.out.println("The sum is" + " " + res);
}

void PQR(String a, String b) {
System.out.println("Thye concataneted string is" + a + " " + b);
}


void PQR(int a, int b, int c) {
int res = a * b * c;
System.out.println("The product is" + " " + res);
}
}

Answer



You need to make a dummy call to nextLine() after your call to nextInt(). The nextInt() isn't taking the "\n" into account.



Alternatively, and preferably, just use nextLine() to accept all input and whichever ones need to be ints, just use:




int i = Integer.parseInt(**string**);


Does this help?


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...