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

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

Related

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;
}

Code Help - Used scanner to initialize string array. When displaying, array values are all blank

I'm currently taking a beginning Computer Science course and for one of our assignments we basically have to create a magic eight ball using an array where the user inputs the amount of values in the array and also inputs the values themselves in the array using a loop. After writing the code, I tested it and found that for some reason it wasn't setting the input into the array like it was supposed to it and after hours tweaking and trying to figure out what's wrong with it I still have no clue. Any help would be much appreciated.
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
input.next(); //It kept skipping the input part the first time
//so I added this
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
out.println("What is your question?");
question = input.nextLine();
input.next();
currentResponse = (int)(Math.random()*numResponses);
out.println(currentResponse);
out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank
spaces
}
out.println("Thank you for using the Magic Eight Ball");
The output should be something like
How many responses would you like there to be?
4 //The input
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[s,d,f,g]
What is your question?
s
0 //The randomized array index number
s //The value of that index
What is your question?
d
2
f
What is your question?
g
1
g
instead it's currently
4
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[, , , ]
What is your question?
s
0 //the randomized array index number
What is your question?
d
2
What is your question?
g
1
input.nextInt(); only consumes the integer entered, it doesn't consume the newline character entered after it. To get around this you can use input.nextLine(); to consume the newline char after it. Then you should be able to remove the input.next(); from the end of the for loop when taking in the responses.
You can also remove the input.next(); within the question loop later on as that's not needed as well -- the input.nextLine(); consumes the whole line.
Here's the adjusted code:
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
System.out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
input.nextLine();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
System.out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
System.out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
System.out.println("What is your question?");
question = input.nextLine();
currentResponse = (int)(Math.random() * numResponses);
System.out.println(currentResponse);
System.out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank spaces
}
System.out.println("Thank you for using the Magic Eight Ball");
}
Some additional documentation: https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html

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

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();
}

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());

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