Saturday, July 28, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...