Java: Getting input with Integer.parseInt(sc.nextLine()) and scan.nextInt() [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I have a Java program below. At first, I tried to get input n as this
int n = sc.nextInt();
But the output was different than expected. It runs the first iteration without taking the userName. After changing to
int n = Integer.parseInt(sc.nextLine());
It's working fine. What was wrong with "int n = sc.nextInt();"?
public class StringUserNameChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Number of usernames you want to enter
int n = Integer.parseInt(sc.nextLine());
while (n-- != 0) {
String userName = sc.nextLine();
System.out.println("Your username is " + userName);
}
}
}

When sc.nextLine() is used after sc.nextInt(), it will read a newline character after the integer input.
So, to run your code correctly, you'll have to use sc.nextLine() after sc.nextInt(), like this:
int n = sc.nextInt();
sc.nextLine();
while(n-- > 0) {
String username = sc.nextLine();
}

Related

How to make two inputs work under same loop? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I am trying to solve a basic problem of finding people with over 5 years of experience. But the code is not running that way.
This is for running two user input command in the same for loop:
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for (int i = 0; i <= n; i++) {
String name = s.nextLine();
System.out.println("enter experience");
int e = s.nextInt();
if (e > 5) {
} else {
}
}
The expected result is the number of people with over 5 years of experience but the actual is the code is asking for experience input only.
When you use nextInt() , you immediately press enter right ?
What is actually happening is that nextInt() takes your integer input , you press enter , now this new line is consumed by String name = s.nextLine(); and the code immediately goes to your System.out.println("enter experience");
What you should be doing is to just simply add another s.nextLine() in the loop like
Scanner s = new Scanner(System.in);
int n = s.nextInt();
String name = s.nextLine();
for (int i = 0; i <= n; i++) {
s.nextLine(); // put this here
System.out.println("enter name");
In this way your new line key is consumed by this new statement and you can now enter your name .
Try this code:
Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());
for (int i = 0; i <= n; i++) {
String name = s.nextLine();
System.out.println("enter experience");
int e = Integer.parseInt(s.nextLine());
if (e > 5) {
} else {
}
}
What you want to do I think is to compare the years of experience after the users are registered. If that is the case then you need to store the users and their stats somewhere like in a HashMap and then filter that HashMap.
You need to clean the buffer somehow.
This maybe helps you.
how to clear input buffer in java
How can I clear the Scanner buffer in Java?
The following will solve it:
Scanner s = new Scanner(System.in);
int n = s.nextInt(); // the input
s.next(); // clean the buffe

save several names in a string array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}

The code runs again no matter what. [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I don't know why, but the below code makes the user run the code again, whether they choose to or not. I've tried many things, but it doesn't work correctly.
Thanks!
public static void main (String [ ] args)
{
boolean a = true;
while (a)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = scan.nextInt();
System.out.print("\n\nEnter a second integer: ");
int z = scan.nextInt();
System.out.println();
System.out.println();
binaryConvert1(x, z);
System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
System.out.print("Enter your response here: ");
String RUN = scan.nextLine();
String run = RUN.toLowerCase();
if (run.equals("n"))
{
a = false;
}
System.out.println();
System.out.println();
}
System.out.println("Goodbye.");
}
Scanner.nextInt() doesn't consume the line ending characters from the buffer, which is why when you read the value of the "yes/no" question with scan.nextLine(), you'll receive an empty string instead of the value the user entered.
A simple way to fix this is to explicitly parse the integer from raw lines using Integer.parseInt():
System.out.print("Enter an integer: ");
int x = Integer.parseInt(scan.nextLine());
System.out.print("\n\nEnter a second integer: ");
int z = Integer.parseInt(scan.nextLine());

Do-while loop inside a method [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
Everything is working fine in this code sample that i did, but everytime it calls the do-while loop on the output screen, it skips the "First name" input, and goes straight to "How old are you?" input. why is that happening and how can i fix it? I want to be able to repeat the whole thing without skipping "First name" when i pick 'y' to perform the loop.
public class WeightGoalTest
{
public static void main(String[]args)
{
doWhile person = new doWhile();
person.userInput();
}
}
import java.util.*;
public class doWhile
{
Scanner keyboard = new Scanner(System.in);
private String inputFn = "";
private int inputAge = 0;
private int inputHeight = 0;
private double inputWeight = 0.0;
private int inputCalculation = 0;
private int inputGender = 0;
private char loop;
public void userInput()
{
do
{
System.out.println("First Name: ");
inputFn = keyboard.nextLine();
System.out.println("How old are you?");
inputAge = keyboard.nextInt();
System.out.println("Gender 1 - Male: ");
System.out.println(" 2 - Female: ");
inputGender = keyboard.nextInt();
System.out.println("What is your Height in inches? ");
inputHeight = keyboard.nextInt();
System.out.println("Current Weight in pounds: ");
inputWeight = keyboard.nextDouble();
System.out.println("\nDo you want to use the calculator again? (y/n)");
loop = keyboard.next().charAt(0);
}while(loop == 'y');
}
}
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
System.out.println("First Name: ");
inputFn = keyboard.next();
use keyboard.next() instead of .nextLine(). For further informations have a look in the Java API concerning the Scanner class. nextLine() will
Advance this scanner past the current line and return the input that was skipped."

Why is my Java while loop making two passes first? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Why is my while loop making two passes before allowing user input? Tried the same with for loop and can't figure out why it's asks for input twice before allowing user to enter input. I know it's a stupid, simple logic mistake I'm making but I'm a noob. Thanks in advance.
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
}
}
Output looks like
How large would you like the array to be? (number)
5
Please type a string to be entered in the array
Please type a string to be entered in the array
Add scan.nextLine(); right after your nextInt:
int arraySize = scan.nextInt();
scan.nextLine();
The first iteration of the while loop is not blocking on the nextLine() because it is picking the new line after the first integer that you input.
Try this:
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
scan.nextLine(); // This advances the Scanner to the next line.
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
}
}

Categories

Resources