Restart while loop if parameters are not fulfilled - java

So, this program works, it runs, but I want it to be idiot proof! And to do that I need some help..
I don´t want it to go to the next line if the user entered a number or nothing at all!
If I press enter without writing anything at all, it still goes to the next line, and the variable navn comes out completely empty at the end.
It does the same thing if I write a number. How do I make it go back and try the same while loop again if for the answer doesn't fulfil the prompts.
Thank you very much:)
import java.util.Scanner;
class Metoder {
public static void main(String[] args) {
String bosted; //Variable
String navn; //Variable
Scanner in = new Scanner(System.in);
System.out.println("Skriv inn navn: "); //What shows up when you first start the program
while (!in.hasNext("[A-Za-z]+")) { //Only allow letters A-Z
in.next();
System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number
}
System.out.println("Takk!"); //Says thank you if the user has entered letters
navn = in.nextLine(); //Proceeds to next line
System.out.println("Skriv inn bosted: "); //Next line, where the user is supposed to enter where he/she lives
while (!in.hasNext("[A-Za-z]+")) { //Excactly the same loop as above
in.next();
System.out.println("Tall hører ikke hjemme i stedsnavn, prøv igjen!");
}
System.out.println("Takk!");
bosted = in.nextLine();
System.out.println("Hei, " + navn + "! Du er fra " + bosted + "."); //Prints out what the user has entered previously in a full sentence.
}
}

Please use this code :
public static void main(String[] args) {
String bosted=""; //Variable
String navn=""; //Variable
Scanner in = new Scanner(System.in);
System.out.println("Skriv inn navn: "); //What shows up when you first start the program
while(in.hasNext()) { //Only allow letters A-Z
navn = in.nextLine();
if(!navn.isEmpty() && navn.matches("[A-Za-z]+")){
System.out.println("Takk!"); //Says thank you if the user has entered letters
in.next();
break;
}
else{
System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number
in.next();
System.out.println("Skriv inn navn: ");
continue;
}
}
System.out.println("Skriv inn bosted: ");
while(in.hasNext()) { //Only allow letters A-Z
bosted = in.nextLine();
if(!bosted.isEmpty() && bosted.matches("[A-Za-z]+")){
System.out.println("Takk!"); //Says thank you if the user has entered letters
break;
}
else{
System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number
in.next();
System.out.println("Skriv inn bosted: ");
continue;
}
}
System.out.println("Hei, " + navn + "! Du er fra " + bosted + "."); //Prints out what the user has entered previously in a full sentence.
}

You can use the continue keyword to restart a loop essentially.
while(!in.hasNext("[A-Za-z]+")) {
try {
String s = in.nextLine();
if(s.isEmpty() || s.matches("^-?\\d+$")){
throw new Exception("empty string or number detected");
}
} catch (Exception e){
continue;
}
}
In that if condition we are checking if the entered string is empty or is an integer, and we can throw an exception which will cause the while loop to continue asking for input until the condition fails (i.e. passes our test).

Related

Java program that asks for user's name and prints it - issue with error message

I have a program that asks for the user's name and prints it back out. It can do that part fine, but it currently has the issue of not printing the proper error message when the user leaves the prompt empty and presses "Enter".
The code:
//Get User Input
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
while (sc.hasNext()) {
//User Input Variable
String name = sc.nextLine();
if (name == null || name.trim().isEmpty()) {
//Error for empty input, keep asking for valid input
System.out.print("Please, what is your name?\n");
sc.next();
} else {
//Print name
System.out.println("Hello " + name + "!");
break;
}//End of conditional
}//End of while loop
The current output:
What is your name?
<blank space for input>
<Empty Space where error message should be>
The ideal output:
What is your name?
<blank space>
Please, what is your name?
What's wrong?
The only thing that you need to change is your condition in the while statement.
Please use sc.hasNextLine() insted of sc.hasNext(). Then you will get desired output. Here is the working soltion:
// Get User Input
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
while (sc.hasNextLine()) { // here is the difference in the code
// User Input Variable
String name = sc.nextLine();
if (name == null || name.trim().isEmpty()) {
// Error for empty input, keep asking for valid input
System.out.print("Please, what is your name?\n");
sc.hasNextLine(); // here is the difference in the code
} else {
// Print name
System.out.println("Hello " + name + "!");
break;
} // End of conditional
} // End of while loop
Scanner sc = new Scanner(System.in);
System.out.print("ENTER YOUR USERNAME : ");
String name = sc.nextLine();
while(name.equals("") || name.trim().isEmpty()) {
System.out.print("PLEASE ENTER YOUR USERNAME AGAIN : ");
name = sc.nextLine();
}
System.out.println("WELCOME " + name);

Loops in Java after user inputs values

public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");

How to avoid double printed statements with an if statement in a while loop

I'm new to stackoverflow and wanted to know why my statement keeps on being repeated twice when i introduce an if statement in my while loop # "if done, type "back"". Secondly, can someone tell me why the ArrayList keeps an empty String at index 0 when i only add one item to the ArrayList? Thanks!
Here is the code:
package com.codewithrichard;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList <String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
System.out.println("1) add item to list");
System.out.println("2) display list and amount of items in it");
System.out.println("3) quit!");
while (appIsStillOn) {
System.out.println("Option (1-4): ");
int option1 = input.nextInt();
if (option1 == 1) {
while (true) {
System.out.println("item (if done, type \"back\"): ");
String itemAdded = input.nextLine().toLowerCase();
if (!itemAdded.equals("back")) {
shoppingList.add(itemAdded);
} else {
break;
}
}
}
else if (option1 ==2){
System.out.println(shoppingList);
System.out.println("size of shopping list: " + shoppingList.size());
}
else {
System.out.println("Can't wait for you to come back!");
appIsStillOn = false;
}
}
}
}
The Scanner#nextInt() method (and many other next...() methods) does not consume the newLine character from the Scanner buffer which is produced when the ENTER key is hit. The Scanner#nextLine() method will consume it if encountered after a Scanner#nextInt() method therefore giving the impression that the prompt for input was skipped over.
Also Consider this...
What is to happen if the User accidentally types in an alpha character instead of a menu choice digit? That's right, your application will crash due to a InputMismatchException.
You should always carry out some form of validation for User input and if that validation fails, allow the User to make a proper entry. This obviously promotes a more trouble free environment when using your application. Using your current model, here is an example of this:
java.util.Scanner input = new java.util.Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList<String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list.");
while (appIsStillOn) {
int option1 = 0;
while (option1 < 1 || option1 > 3) {
System.out.println();
System.out.println("Your Shopping List options are:");
System.out.println(" 1) Add item to list.");
System.out.println(" 2) Display list and amount of items in it.");
System.out.println(" 3) Quit!");
System.out.print("Choice (1-3): --> ");
try{
option1 = input.nextInt();
if (option1 < 1 || option1 > 3) {
throw new java.util.InputMismatchException();
}
/* Consume the enter key hit (newline char) in case
a Scanner#nextLine() prompt is next so that it
doesn't get consumed by that method. */
input.nextLine();
}
catch (java.util.InputMismatchException ex) {
System.err.println("Invalid menu choice supplied! Try again...");
/* Consume the enter key hit (newline char) in case
a Scanner#nextLine() prompt is next so that it
doesn't get consumed by that method. It is also
required here in case an exception has bypassed
the above 'input.nextLine()' call.*/
input.nextLine(); // Consume the enter key hit (newline char)
}
}
if (option1 == 1) {
while (true) {
System.out.println();
System.out.println("Enter the item to add (when done, enter \"back\"): ");
System.out.print("Item: --> ");
String itemToAdd = input.nextLine();
if (itemToAdd.trim().equals("")) {
System.err.println("Invalid Item String! You must supply something!");
continue;
}
else if (itemToAdd.equalsIgnoreCase("back")) {
break;
}
shoppingList.add(itemToAdd);
}
}
else if (option1 == 2) {
System.out.println();
System.out.println(shoppingList);
System.out.println("Number of Items in shopping list: " + shoppingList.size());
}
else {
System.out.println();
System.out.println("Bye-Bye - Can't wait for you to come back!");
appIsStillOn = false;
}
}
After take input input.nextInt(), when you press enter input.nextLine().toLowerCase() takes the data of that line since input.nextInt() doesn't take \n(newline).
Read the newline to skip it after input.nextInt()
int option1 = input.nextInt();
input.nextLine();

How would I split this inputted string? (Java)

I have been working on a program that prompts the user to enter strings, and they are assumed to only enter strings "f name" or "m name." It then lists the names of the males and females entered in separate lists. However, instead of the program listing just the names, it also lists the "f"s and "m"s in front of each name. I tried placing a split method after the user inputs the gender and name, but it doesn't work. I'm sure I'm missing something, but I can't seem to place it. Any help would be appreciated. :)
package labs.lab5;
import java.util.Scanner;
public class NameProcessor {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
UnboundedQueueInterface<String> males;
males = new ArrayUnbndQueue<>(10);
UnboundedQueueInterface<String> females;
females = new ArrayUnbndQueue<>(10);
String input;
do{
System.out.print("Input a gender and name (x done to quit)>");
input = s.nextLine();
input.split(" ");
if(input.startsWith("m"))
{
males.enqueue(input);
}
else if(input.startsWith("f"))
{
females.enqueue(input);
}
else if(input.startsWith("x done"))
{
break;
}
}
while(!input.startsWith("x done"));
System.out.print("males: ");
while(!males.isEmpty())
{
input = males.dequeue();
System.out.println(input + " ");
}
System.out.print("females: ");
while(!females.isEmpty())
{
input = females.dequeue();
System.out.println(input + " ");
}
}
}
Replace males.enqueue(input); with males.enqueue(input.substring(2));
Actually you need to skip first 2 symbols: 'm' (or 'f') and ' '.
You should check for null values and trim the string, but otherwise a simple modification to your code, as follows, works.
do{
System.out.print("Input a gender and name (x done to quit)>");
input = s.nextLine();
String[] tokens = input.split(" ");
if(input.startsWith("m"))
{
males.enqueue(tokens[1]);
}
else if(input.startsWith("f"))
{
females.enqueue(tokens[1]);
}
else if(input.startsWith("x done"))
{
break;
}
}

Where to add an error message to a program finding UPC validation

I need help finishing this code up, I have all of the logic to it and I understand what my code needs to do, I'm just unsure where to add this piece of code to my program and keep everything else running fine.
If i put the code before the while loop without the while wrapped in the else then it works perfectly fine but it throws an exception out of bounds rather than printing the error message and continue on.
If I put the code before the while loop with the while all wrapped in the else it first prompts and after the upc code is input it then prompts again and works fine, but I don't get why it's not doing anything on the first prompt?
thanks in advance!
updated code** it now has trouble with the upc being larger than 12 and if the user enters a blank line, it doesn't print the goodbye statement or the error message, however it does print the error message if the upc is less than 12?
any suggestions would be appreciated greatly!
public class Project06 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a UPC (enter a blank line to quit): ");
String upc = keyboard.nextLine();
while (upc.length() <= 12 && upc.length()>0) {
int odd= Character.getNumericValue(upc.charAt(0))+Character.getNumericValue(upc.charAt(2))
+Character.getNumericValue(upc.charAt(4))+Character.getNumericValue(upc.charAt(6))
+Character.getNumericValue(upc.charAt(8))+Character.getNumericValue(upc.charAt(10));
int even= Character.getNumericValue(upc.charAt(1))+Character.getNumericValue(upc.charAt(3))
+Character.getNumericValue(upc.charAt(5))+Character.getNumericValue(upc.charAt(7))
+Character.getNumericValue(upc.charAt(9));
int sum= odd*3+even;
int checkDigit= Character.getNumericValue(upc.charAt(11));
if (sum%10 !=0) {
int subtract= 10-(sum%10);
if (subtract==checkDigit) {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is valid");
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
upc= keyboard.nextLine();
}
else {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is not valid");
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
upc= keyboard.nextLine();
}
if (upc.length() < 12 || upc.length() > 12){
if (upc.equals("")) {
System.out.print("Goodbye!");
}
else {
System.out.print("ERROR! UPC MUST have exactly 12 digits ");
System.out.println();
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
upc= keyboard.nextLine();
}
}
}
}
}
}
Look over the following code. I have put the input in a method, so you only have to do it once. The upc=null causes the checksum calculation to be skipped and ask for a new upc. I also added an error message if the sum%10 is not right.
Cliff
import java.util.Scanner;
public class upc
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
String upc = inputLine();
while ( upc == null || upc.length() == 12 )
{
if(upc != null )
{
int odd= Character.getNumericValue(upc.charAt(0))+Character.getNumericValue(upc.charAt(2))
+Character.getNumericValue(upc.charAt(4))+Character.getNumericValue(upc.charAt(6))
+Character.getNumericValue(upc.charAt(8))+Character.getNumericValue(upc.charAt(10));
int even= Character.getNumericValue(upc.charAt(1))+Character.getNumericValue(upc.charAt(3))
+Character.getNumericValue(upc.charAt(5))+Character.getNumericValue(upc.charAt(7))
+Character.getNumericValue(upc.charAt(9));
int sum= odd*3+even;
int checkDigit= Character.getNumericValue(upc.charAt(11));
if (sum%10 !=0) {
int subtract= 10-(sum%10);
if (subtract==checkDigit) {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is valid");
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
} else {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is not valid");
System.out.println();
} // if (subtract==checkDigit)
upc = null;
} else {
System.out.println("Bad sum. (sum%10 !=0) = "+(sum%10)+" != 0!"); // WHAT SHOULD HAPPEN HERE?
}
} else upc = inputLine();
} // while
System.out.println("End while");
} // main
public static String inputLine()
{
System.out.print("Enter a UPC (enter a blank line to quit): ");
String upc = keyboard.nextLine();
upc = upc.trim(); // removes any leading and trailing whitespace
if (upc.equals(""))
{
System.out.print("Goodbye!");
System.exit(0);
}
System.out.println(" UPC: "+upc.length()+", '"+upc+"'");
if (upc.length() < 12 || upc.length() > 12)
{
System.out.print("ERROR! UPC MUST have exactly 12 digits ");
System.out.println();
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
} else {
return upc;
}
return null;
}
} // upc

Categories

Resources