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++;
}
}
}
Related
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
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;
}
I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I am trying to create a simple String Revert program that does the following:
Prompts the user for an integer n
Creates an array of n Strings
Keeps reading character strings from user and stores them in the array, until the end of the array or user types "quit"
Prints the strings from the array in reverse order excluding empty slots
Here is my attempt so far:
-However, when i take input and make the size 4, the buffer only reads 3 strings and stops rather than 4.
import java.util.*;
import java.io.*;
class StringRevert {
public static void main(String[] args) {
String myArray[];
Scanner Scan = new Scanner(System.in);
System.out.println("Enter Number: ");
int size = Scan.nextInt();
myArray = new String[size];
for(int i=0; i<myArray.length; i++) {
myArray[i] = Scan.nextLine();
}
}
}
You need to put Scan.nextLine(); before starting of for loop.
public static void main(String[] args) {
String myArray[];
Scanner Scan = new Scanner(System.in);
System.out.println("Enter Number: ");
int size = Scan.nextInt();
myArray = new String[size];
Scan.nextLine();
for(int i=0; i<myArray.length; i++) {
System.out.println("Enter String");
myArray[i] = Scan.nextLine();
}
}
This question already has an answer here:
java.lang.IllegalStateException: Scanner closed
(1 answer)
Closed 4 years ago.
I'm trying to write a program where it will tell you:
The number of integers in a list entered by the user at the command prompt
The sum of those integers.
But I'm having some trouble figuring out how to access those individual numbers. I've tried writing the while loop already, as well as the "if" statements.
Another issue I'm having is that when I try to run my program, I get this error message: Exception in thread "main" java.lang.IllegalStateException: Scanner closed.
NOTE: I'm very new to Java so a simpler solution that mainly uses scanners, next methods, and hasNext methods would be better!
import java.util.Scanner;
public class InputParser
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse?: ");
int numValues = scanner.nextInt();
System.out.println("Please enter " + numValues + " values: ");
while(scanner.hasNextLine())
{
if(scanner.hasNext())
{
if(scanner.hasNextInt())
{
int sum;
System.out.println("The sum of your values is: " + sum + ".");
}
}
scanner.close();
}
}
}
Your code should be like:
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse?: ");
int numValues = scanner.nextInt();
int[] values = new int(numValues);
int sum = 0,i=0;
while(i<numValues)
{ i++;
System.out.print("Enter "+ i+" number : ");
values[i-1] = scanner.nextInt();
sum+= values[i-1];
}
System.out.println("Sum is : "+sum);
scanner.close();
Haven't really consider error handling.
I don't understand why you would ask the user how many numbers they want to sum ahead of time. Basically, your code can be simplified and handle an arbitrary number of numbers. It's also a really bad idea to call close() on a Scanner wrapping System.in (Because you can't re-open it, and if you extract it into a method you will create a hard to debug and find issue). Anyway, you could do something like,
Scanner scanner = new Scanner(System.in);
// System.out.print("How many values do you want to parse?: ");
// int numValues = scanner.nextInt();
System.out.println("Please enter values to sum (type quit to stop)");
int sum = 0; // <-- start at 0.
int count = 0;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
count++;
sum += scanner.nextInt();
} else {
String str = scanner.next();
if (str.equalsIgnoreCase("quit")) {
break; // <-- end the loop.
}
System.out.printf("The value '%s' is not an int (quit to stop).%n", str);
}
}
System.out.printf("The sum of your %d values is %d.%n", count, sum);
// scanner.close(); // <-- Really Bad Idea
Edit Based on your comment,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter values to sum (type quit to stop)");
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
str = (str != null) ? str.trim() : "";
if (str.equalsIgnoreCase("quit")) {
break; // <-- end the loop.
} else if (str.length() == 0) {
continue;
}
int sum = 0; // <-- start at 0.
int count = 0;
Scanner scan2 = new Scanner(str);
while (scan2.hasNextInt()) {
count++;
sum += scan2.nextInt();
}
System.out.printf("The sum of your %d values is %d.%n", count, sum);
}