Simple arrays and for loops. Skipping an input. [duplicate] - java

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I need to create a for loop that fills 2 arrays I have set up. However whenever I run the program. It keeps skipping the next prompt and read in and I have no idea why?
My code is below. It skips the part where I ask them to enter a sentance/word.
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 18/02/2015
* Time: 15:33
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class Week5Q2
{
public static void main(String[] args)
{
final int HOWMANY=5;
Scanner keyboard= new Scanner(System.in);
int choice;
int number [] = new int [5];//mechanism1
String sentence [] = new String [5];
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Please enter a number below");
number[count]=keyboard.nextInt();
System.out.println("\nPlease enter a word below");
sentence[count]=keyboard.nextLine();
}//for
System.out.println("Thank you, now press 1 if you wish to see what you have entered");
choice=keyboard.nextInt();
switch(choice)
{
case 1:
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Here are your numbers");
System.out.println("\n" + number[count]);
System.out.println("Here are your words");
System.out.println("\n" + sentence[count]);
}//for
}//switch
}//main
}//class

You must call nextLine() after nextInt(), to consume the end of the line that contained the int. Otherwise, the end of the line will be consumed when you expect to read the sentence/word.
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Please enter a number below");
number[count]=keyboard.nextInt();
keyboard.nextLine();
System.out.println("\nPlease enter a word below");
sentence[count]=keyboard.nextLine();
}//for

Related

Skipping first String Input when I am giving data in Console [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I want to make a program that will read user inputs and will printout them gradually. But when I am running the code, in the Console area, the first line is automatically skipping. But when I am taking input as Integer, all is running well. Where is my fault?
import java.util.*;
public class MainClass {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int limit, i, j;
System.out.print("How many names you want to take: ");
limit = input.nextInt();
String[] name = new String[limit];
for (i = 0; i < name.length; i++) {
System.out.print("Enter your name: ");
name[i] = input.nextLine();
}
for (String output : name) {
System.out.println("Names are: " + output);
}
}
}
Console area:
How many names you want to take: 3
Enter your name: Enter your name: Saon
Enter your name: Srabon
Names are:
Names are: Saon
Names are: Srabon
Invoke input.nextLine() after the input.nextInt() in order to clear the new line character produced by pressing Enter key (when you enter int number);
Alternatively, you can read your int as Integer.valueOf(input.nextLine()).

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

next() vs nextLine() in JAVA [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was trying to take input for the number of names to be stored in an array from user and then using that i was taking names from the user ,first i tried to take names from the user using next() method and all the things were fine but when i tried to take input using nextLine() method the output was as shown below
package learningJava;
import java.util.Scanner;
public class practice
{
public static void main(String[] args)
{
int n;
Scanner obj = new Scanner(System.in);
System.out.println("Enter the number of names you are gonna enter");
n = obj.nextInt();
String names[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the name of friend "+(i+1));
names[i]=obj.nextLine();
}
obj.close();
System.out.println("Names of your friends are");
for(int i=0;i<names.length;i++)
{
System.out.println(names[i]);
}
}
}
Output for the nextLine() method
Enter the number of names you are gonna enter
5
Enter the name of friend 1
Enter the name of friend 2
It is not prompting me to enter the name of friend 1 and directly skipping it and coming to the friend 2 line.
I am beginner in Java , i know the basic difference in next and nextLine() that next() doesn't take input after a space but nextLine() takes complete input , So what is happening here ??
just in for loop, just change "println" to "print" because nextLine() consumes new line character.
import java.util.Scanner;
public class practice
{
public static void main(String[] args)
{
int n;
Scanner obj = new Scanner(System.in);
System.out.println("Enter the number of names you are gonna enter");
n = obj.nextInt();
String names[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter the name of friend "+(i+1));
names[i]=obj.nextLine();
}
obj.close();
System.out.println("Names of your friends are");
for(int i=0;i<names.length;i++)
{
System.out.println(names[i]);
}
}
}
check this answer: Java String Scanner input does not wait for info, moves directly to next statement. How to wait for info?

Trying to get fresh user input when user's initial input is invalid. But scanner object continues to use first value [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
First of all, apologies for the title gore.
The specific thing I am trying to understand here in the following piece of code is why the getNumber function, when called the second time, continues to return the same initial user input and doesn't ask for a new user input.
/*Write an application that inputs one number consisting
of five digits from the user, separates the number into its individual digits and prints the digits
separated from one another by three spaces each.
*/
public class SeparatingDigitsOfInt {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean check =false;
String s=null;
while (check==false)
{
s= Integer.toString(getNumber()); //since user input was a string, getNumber returns 0 and we enter the while loop below
while (s.equals("0"))// here i am trying to get another input from user because first input was invalid
{
System.out.println("Try that again!");
s= Integer.toString(getNumber()); // why getNumber continues to return xyz here and doesn't ask for new user input
check =false;
}
check =true;
}
System.out.println(s);
while(s.length()!= 5){
System.out.println("Input number is not of 5 digits!");
System.out.println("Please enter a 5 digit number");
s = input.next();
}
String result = "";
for (int i = 0; i < s.length(); i++) {
result= result + s.charAt(i) + " ";
}
System.out.println("Result is :" + result);
}
public static int getNumber(){
try {
System.out.println("Enter a 5 digit number");
return input.nextInt(); // user inputs string xyz
}
catch (InputMismatchException e) {
System.out.println("Please enter only numbers");
return 0;// since user inputs xyz, so 0 is returned by getNumber
}
}
}
In documentation stated :
If the translation is successful, the scanner advances past the input
that matched
So that means if it translation was not successful, it won't advance

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

Categories

Resources