Do-while loop inside a method [duplicate] - java

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."

Related

Last String Input (y/n) is overlooked by the Program. While loop is not breaking

Here is a basic while loop program, where the program at the end should ask the user if you want to keep going or not. The bug is that the program doesn't let me input (y/n) which is the last String Input.
This does not happen when the last input is an integer value.
import java.util.Scanner;
public class lol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
String name = "";
String height = "";
String userOption = "";
while (!userOption.equals("n"))
{
System.out.println();
System.out.print("Enter your name: ");
name = sc.nextLine();
System.out.println();
System.out.print("Enter your age: ");
age = sc.nextInt();
System.out.println();
System.out.print("Enter your height: ");
height = sc.nextLine();
System.out.println();
System.out.println("Do you want to keep going? (y/n)");
// The program over looks this line of code
userOption = sc.nextLine();
if(userOption.equals("y"))
{
System.out.println("Breaking");
break;
}
else
{
continue;
}
}
}
}
See this topic, additional nextLine() call could be a workaround
Scanner is skipping nextLine() after using next() or nextFoo()?
Minor adjustments to the code will fix its behaviour ;)
Scanner sc = new Scanner(System.in);
int age;
String name = "";
String height = "";
String userOption = "";
while (true) {
System.out.print("Enter your name: ");
name = sc.nextLine();
System.out.println();
System.out.print("Enter your age: ");
age = sc.nextInt();
System.out.println();
System.out.print("Enter your height: ");
height = sc.nextLine();
System.out.println();
System.out.println("Do you want to keep going? (y/n)");
// The program over looks this line of code
userOption = sc.nextLine();
if (userOption.equals("y")) {
// nothing
System.out.println("Continuing");
} else {
System.out.println("Stopping");
break;
}
}
System.exit(0);
I would however agree that you should take a look at Scanner is skipping nextLine() after using next() or nextFoo()?

Java is not taking user input for the first variable [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
import java.util.Scanner;
public class NoteIt {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
int Answer;
int i=2;
System.out.print("\nPlease Enter your Name: ");
String Name = s.nextLine();
System.out.println("Welcome to Note-It "+Name+", We hope you'll enjoy our application. ");
String[][] Main = new String[2][2];
Main[0][0]="Create new Note";
Main[1][0]="View My Notes";
System.out.println("\nPlease select what to do: \n");
for(int n=0; n<2; n++){
System.out.println((n+1)+") "+Main[n][0]);
}
System.out.print("\nPlease enter your response: ");
Answer = s.nextInt();
if(Answer == 1){
i++;
Main = new String[i][2];
System.out.print("\nTitle: ");
Main[i-1][0]=s.nextLine();
System.out.print("\nBody: ");
Main[i-1][1]=s.nextLine();
}
}
}
I don't know why it is not asking for Title?
According to #Rohit Jain, That's because the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine returns after reading that newline.
Description here: check this question too
Try this it may help...
Scanner s = new Scanner(System.in);
int Answer;
int i=2;
System.out.print("\nPlease Enter your Name: ");
String Name = s.nextLine();
System.out.println("Welcome to Note-It "+Name+", We hope you'll enjoy our application. ");
String[][] Main = new String[2][2];
Main[0][0]="Create new Note";
Main[1][0]="View My Notes";
System.out.println("\nPlease select what to do: \n");
for(int n=0; n<2; n++){
System.out.println((n+1)+") "+Main[n][0]);
}
System.out.print("\nPlease enter your response: ");
Answer = s.nextInt();
if(Answer == 1){
i++;
Main = new String[i][2];
System.out.print("\nTitle: ");
Main[i-1][0]=s.next();
System.out.print("\nBody: ");
Main[i-1][1]=s.next();
}

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

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