The code runs again no matter what. [duplicate] - java

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

Related

Using scanner to recognize both integers and strings, and stopping user input if a certain string is inputted [duplicate]

This question already has answers here:
How to type a string to end a integer Scanning process in Java
(3 answers)
Closed 2 years ago.
Trying to use scanner to recognize both integers and strings, and stopping user input if a certain string is inputted.
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
Need to make it so if the user types "end", the scanner no longer takes user input. I can't put the line int numberof = myObj.nextInt(); in a loop or something and limit the variable scope, as i'm using that value of numberof throughout the rest of my code.
You can use Scanner#next and then parse integers if needed. I wouldn't recommend just directly using Scanner#nextInt.
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter number of students");
String next = sc.next();
if (next.equals("end")) break;
else {
try {
int num = Integer.parseInt(next);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid input");
}
}
} while (true);

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

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 does my scanner repeat? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I'm trying to make a GPA calculator but early on in the code I started having issues; here's the code segment:
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
}
it all goes well until the "Enter grade (include + or -) " part, it repeats twice, so when I compile and get to that part it says "Enter grade (include + or -) Enter grade (include + or -) " before I can type in anything. How can I fix this repeating issue? Because I think it also takes the spot of one grade.
You can fix this by adding
input.nextLine();
after
int length = input.nextInt();
This will make sure that the end of the line that contained that integer is consumed before you try to read more input.
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
}
Further explanation:
Calling input.nextInt() attempts to read a single token from the standard input and convert it to an int. After you type that integer and hit enter, the input stream still contains the end of line character[s], which haven't been read by input.nextInt(). Therefore, the first time you call input.nextLine(), it reads those characters and then discards them (since input.nextLine() strips newline characters), and you end up getting an empty String. That empty String is assigned to gradesArray[0], and the loop proceeds immediately to the next iteration. Adding an input.nextLine() before the loop solves the problem.

scan.nextLine does not work [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?
(13 answers)
Closed 9 years ago.
I used Java and I tried to write program that reads a number of patients and then let the employee enter their names and ages.
and I want the program reads full name such as (Maha Saeed) so I wrote the code like this but I don't know why it does not work
name = scan.nextLine();
and this is the full code
import java.util.*;
public class Answer1
{
static Scanner scan = new Scanner (System.in);
public static void main (String[] args)
{
int age ;
int PatientNumber ;
int PatientNO;
String name ;
System.out.print("Enter number of patients :");
PatientNumber = scan.nextInt();
PatientNO = 1;
while ( PatientNO <= PatientNumber)
{
System.out.println("Patient #" +PatientNO);
System.out.print("Enter patient's Name: ");
name = scan.nextLine(); //<- here is the problem if I write scan.next it works but it reads only the first name
System.out.print("Enter patient's Age: ");
age= scan.nextInt();
PatientNO = PatientNO + 1;
}
}
}
thanks all
See Why can't I enter a string in Scanner(System.in), when calling nextLine()-method? and Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Simple solution, you can consume the \n character:
scan.nextLine();
name = scan.nextLine();

Categories

Resources