Missing order of display in console when using scanner in java - java

My code is,
public class trueFalse {
public static void main(String[] args){
String sz = null;
do{
String s = null;
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
if(myint<0){
System.out.println("Lessthan zero");
}
else
{
s = getVal(myint);
System.out.println("Value :: "+s);
}
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Do you want to continue ? (YES/no)");
sz = keyboard2.next();
}while(sz.equalsIgnoreCase("yes"));
}
public static String getVal(int num){
return num == 0 ? "ZERO" : "One+";
}
}
When I execute the display order in console as follows,
enter an integer
Value :: One+
Do you want to continue ? (YES/no)
1 #[this one I entered second line in console]
yes
enter an integer
Value :: One+
Do you want to continue ? (YES/no)
3
enter an integer
yes
Where I made mistake ?

There is no need to use two Scanners. You can replace sz = keyboard2.next(); with sz = keyboard.nextLine(); Also, move the Scanner outside your do-while loop.
Also, you'll have to add keyboard.nextLine(); after int myint = keyboard.nextInt();
Here is the corrected code snippet:
public static void main(String[] args) {
/* Move Scanner outside of do-while */
Scanner keyboard = new Scanner(System.in);
String s = null;
String sz = null;
do {
System.out.println("Enter Integer Value: ");
/* Integer Parsing */
String str = keyboard.nextLine();
System.out.println("Entered Integer: " + str);
int myint = Integer.parseInt(str);
if(myint < 0){
System.out.println("Value Less Than Zero!");
}
else
{
s = getVal(myint);
System.out.println("Value :: " + s);
}
System.out.println("Do you want to continue ? (yes/no)");
sz = keyboard.nextLine();
System.out.println("Entered Value: " + sz);
} while(sz.equalsIgnoreCase("yes"));
}
public static String getVal(int num){
return num == 0 ? "ZERO" : "One+";
}
Output:
Enter Integer Value:
Entered Integer: 1
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: yes
Enter Integer Value:
Entered Integer: 2
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: yes
Enter Integer Value:
Entered Integer: 3
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: yes
Enter Integer Value:
Entered Integer: 4
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: no

Related

how do i implement user input in loop in the following code?

this is guess number programme using constructor but the issue which I am facing
is not able to express user input in loop.I tried to look for it but not good explanation.
import java.util.Scanner;
import java.lang.Math;
class guessnumber{
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public String userinput(int repeats,int rand){
String e;
e="that's it";
if(repeats<rand){
String z="choose higher number";
System.out.println(z);
}
else if (repeats>rand){
String z="choose lower number";
System.out.println(z);
}
return e;
}
public String iscorrect(){
String correct="correct number";
return correct;
}
}
public class guessthenumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
guessnumber gun = new guessnumber();
System.out.println("enter number ");
int number = sc.nextInt();
System.out.println("enter max and min number");
int min = sc.nextInt();
int max = sc.nextInt();
int o=gun.getRandomNumber(min,max);
System.out.println(o);
if (number < o || number > o) {
System.out.println(gun.userinput(number, o));}
else if(number==o){
String correct= gun.iscorrect();
System.out.println(correct);
}
}
}
I want to user to keep entering data till correct number is hit
Here's a solution that behaves like you're describing, and how your code currently behaves:
ask for a few numbers up front (minimum, maximum)
determine a random "target" number for the user to guess
ask the user to guess – if they're correct, show a message; if they're incorrect, ask for another guess
repeat until their guess is correct
A few things I did:
introduce a "getNumber()" helper that will make sure the numbers make sense – put some guardrails around what a user can enter to minimize unexpected results if user enters unexpected input
use a "while" loop, go forever – while (true)
if their guess matches the target, use break to stop the loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimum = getNumber(scanner, 0, "minimum");
int maximum = getNumber(scanner, minimum + 1, "maximum");
int target = (int) ((Math.random() * (maximum - minimum)) + minimum);
while (true) {
System.out.print("enter a guess: ");
int guess = scanner.nextInt();
if (guess == target) {
System.out.println("correct guess! the number was " + target);
break;
} else {
System.out.print("nope, please try again.. ");
}
}
}
static int getNumber(Scanner scanner, int minimumAllowed, String numberType) {
while (true) {
System.out.print("enter " + numberType + " number: ");
int minimum = scanner.nextInt();
if (minimum >= minimumAllowed) {
return minimum;
} else {
System.out.println("too small, must be at least " + minimumAllowed);
}
}
}
Here's a sample run:
enter minimum number: 1
enter maximum number: -3
too small, must be at least 2
enter maximum number: 5
enter a guess: 1
nope, please try again.. enter a guess: 2
nope, please try again.. enter a guess: 3
nope, please try again.. enter a guess: 4
correct guess! the number was 4
You can use while and break statements

Errors in Java check integer is inputted

I know that the question has been asked but I tried to apply what I saw here and got an error.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
// If the input isn't an int, the loop is supposed to run
// until an int is input.
get_input.hasNextInt();
year_of_birth = get_input.nextInt();
}
//year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
Without the loop, everything works fine. What is wrong in my code? To be clear, I'm trying to ask for an input until the input can be validated as an integer.
Thanks a lot in advance.
If you would like to skip invalid non-int values, your loop should look like this:
while (!get_input.hasNextInt()) {
// skip invalid input
get_input.next();
}
// here scanner contains good int value
year_of_birth = get_input.nextInt();
This works for me if i understood you correctly. You need to keep checking what value has the scanner, so you need to keep advancind through the scanner while the value is not an integer:
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) { //check if it is not integer
System.out.println("Enter your year of birth"); // ask again
get_input.next(); //advance through the buffer
}
year_of_birth = get_input.nextInt(); //here you get an integer value
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();

Accept only 8-digit numbers

I have this assignment and I need help when I try to change sales value it does not change and when I enter the Id for salesperson must be accept 8 digit numbers not more or less
I tryed .....but I stoped here.
else {
System.out.print("Please enter your ID : ");
String ID = scanner.nextLine();
//Declaration
boolean exists = checkIfIDExists(ID);
if(exists) {
System.out.print("Please enter new sales value : $");
float newSalesValue = scanner.nextFloat();
Iterator<Salesperson> iterator = salespersons.iterator();
while(iterator.hasNext()) {
Salesperson salesperson = iterator.next();
if(salesperson.getID().equals(ID)) {
salesperson.setAnnualSales(newSalesValue);
}
}
}
accapet 8 digit numbers
}
else {
System.out.print("Please enter your ID : ");
String ID = scanner.nextLine();
boolean ifValid = validateID(ID, salespersons);
if(MAX_ID_CHAR_COUNT != ID.toCharArray().length) {
} else {
System.out.print("Please enter eight digits of your ID : ");
ID = scanner.nextLine();
// Declaration and loop
}
//if = validateID(ID, salespersons);
if(ifValid) {
System.out.print("Duplicate digits. Please enter eight digits of your ID : ");
ID = scanner.nextLine();
}
using a loop to validate you id is valid ,that is a code
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
boolean ifValid=false;
String ID;
//using loop to validate this id is valid and length is 8
do{
System.out.print("Please enter your ID : ");
ID = scanner.nextLine();
ifValid= validateID(ID, salespersons);
if (!ifValid){
System.out.print("Duplicate digits. Please enter eight digits of your ID : ");
}
}while (!ifValid);
System.out.print("Please enter eight digits of your ID : ");
ID = scanner.nextLine();
}
private static boolean validateID(String id, Object salespersons) {
return id!=null&&8==id.length();
}

Java Do While Validation

How do I change this while(true) into a do while so when the user enters a number they will be given back details but if they enter * the system will close.
while (true){
System.out.print("Enter number: ");
int option = keyboard.nextInt();
out.writeInt(option);
char option;
do {
System.out.print("Enter number: ");
option = keyboard.nextChar();
out.writeChar(option);
} while (option != '*')
You may want to use nextLine() or next() to receive the input and parse them accordingly:
do{
System.out.print("Enter number: ");
String str = keyboard.nextLine();
int option = 0;
if(str.matches"[0-9]+"){
option = Integer.parseInt(str);
System.out.println(option);
}
else if(str.equals("*"))
System.exit(0); //or use break; if you want to exit the loop
}while(whatever); //whatever == true
If you change it to allow the user to input a String and then convert to int if possible, you can catch any errors and break out if the user enters a '*' character:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option;
String input;
do{
System.out.print("Enter number: ");
input = keyboard.nextLine();
try{
option = Integer.parseInt(input);
System.out.println("You entered the value: " + option);
}
catch(Exception ex) {
if (!input.equals("*")){
System.err.println("Invalid input, please enter numbers only.");
}
}
}while(!input.equals("*"));
}
}
If you use an exit value like (-1), you can continue to process input with nextInt() and becomes even easier. You can do this with a simple do/while:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option = 0;
do{
System.out.print("Enter number: ");
option = keyboard.nextInt();
System.out.println("You entered the value: " + option);
}while(option != -1);
}
}
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
}while(!str.equals("*"))
edit: if you want to play with numbers as integer or double. Just let me know and I'll add casted version as your needs.
int number;
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
number = Integer.parseInt(str);
}while(!str.equals("*"))
now you have a integer number.

why does this code not let me input a command after the calculator class is done?

I am trying to make a simple text based operating system and I cant figure out why my code doesn't let me enter a command after the calculator class is done. It is supposed to continue executing the code until I type "off" but this is not the case. Eclipse says it is running but I cant do anything. can someone please help me?
here is my two classes:
public class Calculator extends Start{
public static void calStrt() {
System.out.print("\nEnter operator you wish to use: ");
StringInput = scan.nextLine();
if (StringInput.equals("+")) {
add();
} else if (StringInput.equals("-")) {
sub();
} else if (StringInput.equals("*")) {
mul();
} else if (StringInput.equals("/")) {
div();
} else {
System.out.println("\nSyntax error: Operator not recognized");
System.out.println("Please try again");
calStrt();
}
}
public static void add() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 + intVar2));
}
public static void sub() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 - intVar2));
}
public static void mul() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 * intVar2));
}
public static void div() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 / intVar2));
}
}
import java.util.Scanner;
class Start {
static Scanner scan = new Scanner(System.in);
static String StringInput;
static int intInput;
public static void main(String[] args) {
System.out.println("\nWelcome to RobOS");
passLoop: while (true) {
System.out.print("\nPlease enter password: ");
StringInput = scan.nextLine();
if (StringInput.equals("banana")) {
System.out.print("Logging in, please wait");
System.out.print(".");
System.out.print(".");
System.out.println(".");
System.out.println("\nWelcome User");
outerLoop: while (true) {
System.out.println("\nType \"help\" to see a list of programs");
StringInput = scan.nextLine();
innerLoop: while (true) {
if (StringInput.equalsIgnoreCase("cal")) {
Calculator.calStrt();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("guess")) {
GuessGame.guess();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("help")) {
System.out.println("\n\"cal\" uses the calculator");
System.out.println("\"guess\" plays guessing game");
System.out.println("\"help\" shows list of programs");
System.out.println("\"off\" turns RobOS off");
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("off")){
break passLoop;
}
}
}
} else {
System.out.println("\nWrong password. Please try again");
continue passLoop;
}
}
}
}
Brent Nash is correct. To fix the error though, try using instead of scan.nextInt(): Integer.parseInt(scan.nextLine());
Hope this works
Your code is getting into an infinite loop. When you call StringInput = scan.nextLine(), the first time it works fine. I entered cal and I can run the calculator once. The problem is that the second time scan.nextLine() gets called, it's automatically returning an empty string "" as the value of StringInput. Your set of if/else statements in the while(true) have no way to handle this, so it just loops forever.
The deeper rationale is that you call scan.nextInt() to read in the numbers, but the problem is when you read in the second number for the calculator operation, there's still a "\n" sitting on System.in. As a result, when you loop around and call scan.nextLine() again, it doesn't prompt you for anything because it just reads that "\n" that's still sitting on System.in and then that sends you into an infinite loop.

Categories