Scanner using with while loop and switch statement - java

I'm creating a simple console app in Java and I have a trouble. This is my code:
boolean isActive = true;
Scanner scanner = new Scanner(System.in);
do {
try {
int option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("Search By Registration number: " +
"\n------------------------------");
System.out.println("Enter registration number!");
String regNumber = scanner.nextLine();
if (regNumber == incorrect) {
continue; // return to case 1 and ask enter regnumber one more time
} else {
// do stuff
}
break;
case 2:
System.out.println("Exit the search option: ");
isActive = false;
break;
default:
System.out.println("Your selection was wrong. Try one more time!");
break;
}
} catch (InputMismatchException ex) {
System.out.println("Your selection was wrong. Try one more time!");
}
scanner.nextLine();
} while (isActive);
And I can't to return to case 1 if an error occured. So, if error occured, the user must get the message About entering the registration number one more time and so on.

You need to use equals() when you check a regNumber
if (regNumber.equals(incorrect)) {
System.out.println("Incorrect!");
continue;
} else {
System.out.println("Correct!");
}
But even then, your program doesn't work properly, change String regNumber = scanner.nextLine() on this:
String regNumber = scanner.next();

You could put a loop around your input for the regNumber, in order to listen for input while it's not correct.
String regNumber = incorrect;
// String is a reference type, therefore equality with another String's value
// must be checked with the equals() method
while(regNumber.equals(incorrect)){
if (regNumber.equals(correct)) {
// Do something if input is correct
}
}
This may be not the exact solution you wanted, but think of the same concept and apply it to your program. Also see this for more information about String comparison. Hope this helped!

Related

More efficient way to handle user input data validation?

In Java, I have two while loops to validate user input and continuously prompt the user if they input the wrong data type. In this program, I only have 2 questions, but I can imagine a scenario where I have more than 10, at which point 10 while loops would be cumbersome code to read and maintain. Is there a more efficient way to check for errors while continuing to prompt the user? My initial thought is to package the while loop and error checks into a separate class function and call it when input is requested.
import java.util.*;
public class IncreaseAge {
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
boolean validInput = true;
String coolName = "Adam";
int coolAge = 0;
while(validInput){
try{
System.out.print("Hello, what is your first name? ");
coolName = userInput.nextLine();
validInput = false;
}
catch(Exception error){
System.out.println("Invalid input, try again!");
userInput.next();
}
}
validInput = true;
while(validInput){
try{
System.out.print("Hi "+ coolName + "! How old are you?");
coolAge = userInput.nextInt();
validInput = false;
}
catch(Exception error){
System.out.println("Invalid input, try again!");
userInput.next();
}
}
System.out.println("Hello "+ coolName + ", in ten years you will be " + (coolAge+10));
userInput.close();
}
}
Just implement private int getIntegerInput(String prompt) and private String getStringInput(String prompt), each of which will more or less be the same as the two loops you've already coded.
This is a common and frequent way to avoid code repetition - implement "helper" routines to be used in writing your intended functionality.
Even if you don't have repetition to worry about, it's a useful partitioning of code, making it easier to understand - for example, the "get an input" code is clearly distinct from the "process the input" code.
Example:
private String getStringInput(Scanner scanner, String prompt) {
String input = null;
boolean validInput = false;
while (!validInput) {
try {
System.out.print(prompt);
input = scanner.nextLine();
validInput = !input.isEmpty();
}
catch (Exception error) {
System.out.println("Invalid input, try again!");
}
}
return input;
}
Note that I fixed the use of 'validInput' to make sense, and I assume you want to reprompt on an empty input line.
Usage is then like
String coolName = getStringInput(userInput, "What is your first name? ");

JAVA how to write an exception if the user entered a number instead of a string?

Please explain I'm a little confused with do while .
If I enter the name of the city the first time, everything works correctly.But if I enter a number, I get a corresponding message, and when I try to enter the name of the city for the second time, it gives the same message.(about invalid data)
String town=scanner.nextLine();
boolean tryagain = false;
do {
if (town.charAt(0) >= '0' && town.charAt(0) <= '9'){
System.out.println("You probably entered an invalid data format");
scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
}while (tryagain);
I also tried the try and catch option, but I couldn't write an exception if the user entered numbers instead of a string.It doesn't work. Help please.
try {
System.out.println("enter the name of the city");
town = scanner.nextLine();
} catch (InputMismatchException e) {
System.out.println ("You probably entered an invalid data format ");
scanner.nextLine();
}
Note the difference between this line of code:
town = scanner.nextLine();
and this line of code:
scanner.nextLine();
They both accept input from the console, but only one of them stores that input in the town variable. To update the town variable with the newly entered value, store that value in that variable:
town = scanner.nextLine();
Try this. Inside if block save scanner.nextLine() to town variable in order to check in the next iteration if it consists only from numbers or it is empty:
Scanner scanner = new Scanner(System.in);
String town=scanner.nextLine();
boolean tryagain;
do {
if (town.matches("[0-9]*")){
System.out.println("You probably entered an invalid data format");
town = scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
} while (tryagain);
put it inside try block and try parsing it as Integer
try{
Integer.parseInt(town)
}catch(NumberFormatException nfe){
//this is a string otherwise it would be number
}

First if conditions not working correctly

When I run my code it works fine until it gets to the point where my if statement evaluates the answer string. It will always run the first if statement no matter what I input into the scanner object. And if I take out the scanner.nextLine(); then it will not let me enter any input for the answer object.
public class ExceptionTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean statement = true;
int total;
String answer = null;
do{
try{
System.out.println("Please enter the amount of Trees:");
int trees = scanner.nextInt();
if(trees < 0){
throw new InvalidNumberException();
}
System.out.printf("Amount of fruit produced is: %d%n", trees * 10);
System.out.println("Please enter the amount of people to feed: ");
int people = scanner.nextInt();
scanner.nextLine();
total = trees * 10 - people * 2;
System.out.printf("The amount of fruit left over is: %d%n", total);
statement = false;
}
catch(InvalidNumberException e){
System.out.println(e.getMessage());
scanner.nextLine();}
}
while(statement);
System.out.println("Would you like to donate the rest of the fruit? Y or N:");
try{
answer = scanner.nextLine();
if(answer == "Y"){
System.out.println("Your a good person.");
}else if(answer == "N"){
System.out.println("Have a nice day.");
}else {
throw new NumberFormatException();
}
}
catch(NumberFormatException e){
System.out.println(e.getMessage());
scanner.nextLine();
}
}
}
There are three things here:
The first call to scanner.nextLine() gets the user input, but isn't stored in a variable. The answer variable is storing a second, unnecessary, call to scanner.nextLine(). EDIT The reason why scanner.nextLine() is needed is the previous scanner call is to scanner.nextInt(). nextInt() doesn't move the cursor to the next line. See: Scanner is skipping nextLine() after using next() or nextFoo()?.
You can't compare Objects using == and !=. Java's comparison operators test for strict object equality. You don't mean to check for whether they are the same String instance, you mean to check if the two instances store the same text. The correct comparison is !answer.equals("Y").
Think about the logic of the if statement. Think about what the || operator means.
I have seen that you edited your answer which was good because the logic was wrong in there. You should check first if the input was Y or N before verifying it is not in the two. Your problem is pretty simple, it is a common problem regarding the scanner class. Just add String trash = scanner.nextLine(); and remove many unnecessary scanner.nextLine();
String trash = scanner.nextLine();
System.out.println("Would you like to donate the rest of the fruit? Y or N:");
try {
answer = scanner.nextLine();
if (answer.equals("Y")) {
System.out.println("Your a good person.");
} else if (answer.equals("N")) {
System.out.println("Have a nice day.");
} else {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
Add String trash whenever the Scanner messes up in your case it was near the answer=scanner.nextLine(); If there are still errors just comment. I am happy to help

java : how can i use if correctly

I recently started java programming
but I have a problem
i want to write a program. I have a password, I ask the user of the program to enter the password
I want: if the person entered a string, I tell him that please don't enter string
and if the password was right and the type of the password that he entered(int) was right, I tell him OK.
in the test of the program, my problem is that when I entered a wrong password and expect that the program tell me that the pass is wrong, the program just tell me nothing !!
here is my code :
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass)
{
System.out.println("ok");
}
else if (password.hasNextInt())
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
You are using hasNextInt() From Java docs.
Returns true if the next token in this scanner's input can be
interpreted as an int value
So you are asking twice for the input.
Example
Input:
1234 (first Input)
1234 (Then hasNextInt() is asking for input again)
OutPut :
wrong pass
So I made this simple snippet for you can use
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
int pass = 123;
try {
int myInput = password.nextInt();
if (myInput == pass) {
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (java.util.InputMismatchException e) {
System.out.println("wrong type");
}
The problem is that Scanner methods like nextInt() consume input that's then no longer available to later Scanner calls.
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass) // line A
{
System.out.println("ok");
}
else if (password.hasNextInt()) // line B
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
So in case of entering a wrong password, e.g. 4321, what happens?
Line A checks password.hasNextInt() as the first half of your condition. The Scanner doesn't know that right now and waits for your console input. You enter 4321, and now the Scanner can check whether that's a valid number (and it does so without consuming the 4321, so that it's still available). It is, so the program continues to the next part of the condition (side remark: were it abc, that first part would be false, and Java would already know that the combined password.hasNextInt() && password.nextInt()==pass condition would be false, without a need to go into the second half, thus not consuming the entry).
Line A now checks the second half password.nextInt()==pass. This calls nextInt(), returning the integer 4321 and consuming the input. Comparing this against your number 123 gives false, so the condition doesn't match. That's what you want so far.
Now in line B you want to check for the case of a number not being 123. But your condition password.hasNextInt() no longer sees the 4321 we entered, as that has been consumed in line A. So it waits for the next input. That's the problem, you're still calling hasNextInt() after consuming the input with nextInt().
You can change your program like this:
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt()) {
if (password.nextInt()==pass) {
System.out.println("ok");
} else {
System.out.println("wrong pass");
}
} else {
pass.next(); // consume the invalid entry
System.out.println("wrong type");
}
[ I reformatted the code snippet in a more Java-typical style, doesn't change the functionality of course, but looks more familiar to me. ]
Of course, Gatusko's exception-based approach works as well, and personally I'd do it his way, but maybe you don't feel comfortable with exceptions right now, so I stayed as close to your approach as possible.
You can use the following piece of code.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt())
{
if(password.nextInt()==pass) {
System.out.println("ok");
}
else {
System.out.println("Wrong password");
}
}
else
{
System.out.println("wrong type");
}
}
What about a while?
int MAX_TRIES = 3
int currentTries = 0;
while (password.hasNextInt() && currentTries < MAX_TRIES) {
if (password.nextInt()==pass) {
// OK!
} else {
// Wrong!
}
currentTries++;
}
if (currentTries == MAX_TRIES) {
// You tried too much
} else {
// Password was a string
}
Try this code, if the input is not an integer then it will throw NumberFormatException, which is caught and displayed.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
String enteredPassword ="";
if(password.hasNext() && (enteredPassword = password.next()) !=null){
try{
if(Integer.parseInt(enteredPassword) == pass){
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (NumberFormatException nfe){
System.out.println("wrong type");
}
}
}

java try and catch..infinite loop

I am having a problem with try and catch. My program is to insert three different strings name, address and phone number then I convert these three in to a single String using toString method.
I have problem with exception handling whenever I write a wrong choice (String or other data type) then catch works infinity times.
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<String> arraylist= new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format="Empty";
int x=1;
int flag=0;
do
{
try
{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice=input.nextInt();
switch (choice)
{
case 1:
{
System.out.println("Enter name ");
name=input.next();
System.out.println("Enter phone number");
phoneNumber=input.next();
System.out.println("Enter address");
address=input.next();
format=FormatObject.toString(phoneNumber, name, address);
arraylist.add(format);
flag++;
}
break;
case 2:
{
System.out.println("Name Phone number Address");
System.out.println();
for(int i=0;i<flag;i++)
{
System.out.println(arraylist.get(i));
}
}
break;
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");`
}while(x==1);
}
}
//The format class ...//returns format for string
Your try and catch are not related to a loop, nor to your problem.
while(x==1)
is what you test on, yet you never change the value of x, so it will always remain 1, and thus the above check will always return true.
I think I now know what your problem actually is.
Simply adding input.nextLine() at the very beginning at your code will stop the input running havoc.
boolean wrongInput = false;
do {
try {
if (wrongInput) {
input.nextLine();
wrongInput = false;
}
System.out.println("Enter your choice");
[...]
} catch (...) {
wrongInput = true;
}
should do the trick. However, please note that I noticed two errors in your program (which might be because I do not have the CreateFormat class of yours), (a) I cannot add a number to the address and (b) there is no option to stop the loop (which I strongly recommend - where you simply set x = -1 or something similar, better use a boolean to end the loop though).

Categories

Resources