How to validate string from user input to pre defined name [duplicate] - java

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
Hello all I am trying to write a loop in my code that would prompt user if they enter something other than what I have predefined. I am somewhat familiar with this done to user input that is not specific word or int but not sure when user has three choices to choose from.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
// this class will instantiates player object
public class Adventure {
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
List<String> names = Arrays.asList("mage","archer","warrior");
String userinput;
while (myinput.hasNext()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "
+ gameplayer.getClassName()+ ". What health do you have?");
}
}
int healthofPlayer ;
while (myinput.hasNextInt()){
healthofPlayer = myinput.nextInt();
if ((!myinput.hasNextInt())){
System.out.println("I'm sorry, what was that?");
}
else {
gameplayer.setHealth(healthofPlayer);
System.out.println("Very good. Now let's get started on your adventure.");
System.out.println("You awake alone, disoriented, and locked in the CS1331 TA Lab.");
}
return;
}
}
}

try out this, it should work out the rest.
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
List<String> names = Arrays.asList("mage","archer","warrior");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
String userinput;
while (myinput.hasNext() || myinput.hasNextInt()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "+ gameplayer.getClassName()+ ". What health do you have?");
int numberofHealth = myinput.nextInt();
}
System.out.println("Very good. Now let's get started on your adventure.");
gameplayer.setHealth(numberofHealth);
return;
}
}

There's no need loop for this. It'll be easier to delegate to a function as you'll see.
List<String> acceptable = Arrays.asList("mage", "archer", "warrior");
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
gameplayer.setclassName(promptFor(acceptable));
// having a function for this encapsulates the looping and the checking
// as well as the reprompting - it also means we can leave the loop
// with the right answer
String promptFor(Set<String> acceptable) {
while(true) { // while true sucks, but you've asked for an indefinite loop
String next = myinput.next().toLowerCase();
if (acceptable.contains(next)) {
return next;
}
// so it was a bad input
System.out.println("I'm sorry, what was that?");
} // loop some more
return null; // unreachable code
}

Related

Repeatedly Ask user for input, if input is not an integer [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 1 year ago.
As the title says, i'm attempting to make my program re-ask for user input if the given input is invalid (In this case, invalid input is any input that is not an integer)
I've already tried this, but it does not work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
} else {
System.out.println("This input is not an integer - Please try again!");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
}
}
}
I'm aiming for this to be done with while loop and scanner
My current code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
}
}
}
Any reply on this post is greatly appreciated.
You can use while-loop:
Scanner scanner = new Scanner(System.in);
boolean ageGiven = false;
while (!ageGiven) {
System.out.println("Please input your age");
String next = scanner.next();
try {
int age = Integer.parseInt(next);
System.out.println("Your age is: " + age);
ageGiven = true;
} catch (NumberFormatException e) {
System.out.println("This input is not an integer - Please try again!");
}
}
I think you should put while instead of if statement. Break after having correct input. Try out once.
As you suggested, a while loop is more appropriate to this.
Something like this should work:
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
boolean isValid = false;
int age;
while (!isValid) {
if (scanner.hasNextInt()) {
age = scanner.nextInt();
isValid = true;
}
else {
System.out.println("Invalid input. Please type a number");
}
}
System.out.println("Your age is: " + age);
In this case, it would loop while the IsValid boolean is false. And that variable would be set to true, once the user inputs a valid age.
Edit: Changed the code to check if the input is an integer.

When I execute my program the program displays java.util.NoSuchElementException: No line found [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 2 years ago.
I'm a bit new to java, and I am wondering what I did wrong in my code. The problem is at "System.out.println(pw.next());" This code is for a Pokemon like game, and the scanner is supposed to scan for the person's username. I am far from finished with the code, and the layout is a bit weird because I tried fixing the error myself.
It would also be highly appreciated if anyone has tips for creating a fun game.
package test;
import java.lang.Math;
import java.util.*;
public class Pokemon {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Daniel's Game");
System.out.println("\nFire. Water. Earth. Air. The four nations lived in harmony until the Avatar attacked. \nFueled by anger, this avatar, whose name remains unknown, has sought to take over the world.\nLegends say that he lives deep in the Himalayas and wields the power of all four elements, but nobody can say for sure");
System.out.println("It is your job to save the world from catastrophe");
System.out.println("Are you up for the Challenge?");
String y = sc.next();
if(y.equals("yes")||y.equals("Yes")) {
System.out.println("You better be");
} else {
System.out.println("The world ends cuz you suck");
System.exit(0);
}
sc.close();
name();
}
public static void name() {
System.out.println("What is Your Name?");
Scanner pw = new Scanner(System.in);
String o = pw.next();
pw.close();
Scanner ew = new Scanner(System.in);
System.out.println("\nChoose a Pokemon: \n1. Fire \n2. Water\n 3. Earth \n4. Air");
int x = ew.nextInt();
ew.close();
}
}
Below should work :
package test;
import java.lang.Math;
import java.util.*;
public class Pokemon {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("Welcome to Daniel's Game");
System.out.println("\nFire. Water. Earth. Air. The four nations lived in harmony until the Avatar attacked. \nFueled by anger, this avatar, whose name remains unknown, has sought to take over the world.\nLegends say that he lives deep in the Himalayas and wields the power of all four elements, but nobody can say for sure");
System.out.println("It is your job to save the world from catastrophe");
System.out.println("Are you up for the Challenge?");
String y = sc.next();
if(y.equals("yes")||y.equals("Yes")) {
System.out.println("You better be");
} else {
System.out.println("The world ends cuz you suck");
System.exit(0);
}
// sc.close();
name();
}
public static void name() {
System.out.println("What is Your Name?");
String name = sc.next();
// Scanner pw = new Scanner(System.in);
// String o = pw.next();
// pw.close();
//Scanner ew = new Scanner(System.in);
System.out.println("\nChoose a Pokemon: \n1. Fire \n2. Water\n 3. Earth \n4. Air");
int x = sc.nextInt();
sc.close();
}
}
Maybe your errors happened because you use Scanners in a bad way, just one is enough and pass it as a parameter through the main class is a good custom because you can close it after the function is terminated.
Try this...
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Daniel's Game");
System.out.println("\nFire. Water. Earth. Air. The four nations lived in harmony until the Avatar attacked. \nFueled by anger, this avatar, whose name remains unknown, has sought to take over the world.\nLegends say that he lives deep in the Himalayas and wields the power of all four elements, but nobody can say for sure");
System.out.println("It is your job to save the world from catastrophe");
System.out.println("Are you up for the Challenge?");
String y = sc.next();
if (y.equals("yes") || y.equals("Yes")) {
System.out.println("You better be");
} else {
System.out.println("The world ends cuz you suck");
System.exit(0);
}
name(sc);
sc.close();
}
public static void name(Scanner sc) {
System.out.println("What is Your Name?");
String o = sc.next();
System.out.println("\nChoose a Pokemon: \n1. Fire \n2. Water\n 3. Earth \n4. Air");
int x = sc.nextInt();
}

Trying to call a method in another class to use in a IF statement

I am trying to call a class when running an IF statement which will ask the user if they want to view the program in English or Spanish. The Spanish Code is in a different class and I want to call is so when/if the user chooses to view the program in Spanish and disregards the English code written below.
Error: Java cannot find symbol
symbol: method Spanish()
location: variable span of type source.Spanish
Below is my second class(that I want to call):
package source;
import java.util.Scanner;
import java.lang.String;
public class Spanish {
public Spanish() {}
}
And below is how I am trying to call in my main class:
if (language.equals("Span")) {
source.Spanish span = new source.Spanish();
span.Spanish();
}
else {
//More code.
}
My first time asking a question so I am sorry if the format isn't right or if the question has already been answered, I looked at a few of the past questions but no luck so far. Thank you :)
EDIT
package source;
import java.util.Scanner;
import java.lang.String;
public class CashRegister {
public static void main(String[] args) {
String registerfloat;
String input;
String name;
String anotherTransaction;
String item2;
String choice;
String language = "";
double balance;
double cost;
double change = 0;
double cash = 0;
double amountRequired = 0;
double totalAmount = 0;
Scanner in = new Scanner(System.in);
System.out.println("Hello! Welcome to the Cash Register.\n");
while (true) {
if (language.equals("Eng"))break;
if (language.equals("Span"))break;
else {
System.out.println("Which language would you like to use? English (Eng) or Spanish (Span)?:");
language = in.nextLine();
}
}
if(language.equals("Span")) {
source.Spanish span = new source.Spanish();
span.Spanish();
}
else {
System.out.print("Please enter cash register's float: $");
registerfloat = in.nextLine();
balance = Double.parseDouble(registerfloat);
boolean loop = true;
while (loop == true) {
System.out.println("Do you wish to continue this transaction?: (Yes/No)");
choice = in.nextLine();
loop = false;
switch (choice) {
case "Yes":
System.out.print("Please enter the item's name:\n");
input = in.nextLine();
name = input;
System.out.print("Please enter the item's cost:");
input = in.nextLine();
cost = Double.parseDouble(input);
System.out.println("Do you wish to add another item?: Yes/No");
item2 = in.nextLine();
while (true) {
if (item2.equals("No"))
break;
else {
System.out.print("Please enter the item's name:\n");
input = in.nextLine();
name = input;
System.out.print("Please enter the item's cost:");
input = in.nextLine();
cost = Double.parseDouble(input);
System.out.println("Do you wish to add another item?: Yes/No");
item2 = in.nextLine();
}
}
Transaction trans = new Transaction(name, cost);
amountRequired = amountRequired + trans.getCost();
totalAmount = totalAmount + trans.getCost();
System.out.print("Please enter the cash amount tendered: $");
input = in.nextLine();
cash = cash + Double.parseDouble(input);
amountRequired = amountRequired - cash;
balance = balance + cash;
change = cash - totalAmount;
System.out.println("Amount of change required = " + change);
loop = true;
break;
case "No":
balance = balance - change;
System.out.print("Balance of the Cash Register: $" + balance + "\n");
System.out.println("\nThank you for using the Cash Register!");
System.exit(0);
default:
loop = true;
System.out.println("Wrong input, try again!");
break;
}
}
}
}
}
Above is my entire code from CashRegister. "Spanish" has the EXACT same code except the print statements are in Spanish rather than English. Also, sorry if its hard to read or there is unnecessary stuff in there, its a group assignment and in early stages so is a bit of a mess. Cheers
Update 2
package source;
import java.util.Scanner;
public class RunClass {
public static void main(String[] args) {
String registerfloat;
String language = " ";
double balance;
Scanner in = new Scanner(System.in);
System.out.println("Hello! Welcome to the Cash Register.\n");
System.out.print("Please enter cash register's float: $");
registerfloat = in.nextLine();
balance = Double.parseDouble(registerfloat);
while (true) {
if (language.equals("Eng")) break;
if (language.equals("Span")) break;
else {
System.out.println("Which language would you like to use? English (Eng) or Spanish (Span)?:");
language = in.nextLine();
}
}
if (language.equals("Eng")) {
source.CashRegister.CashRegister();
}
else {
// trying to enter Spanish.register here but it does not even show as its not on the current branch.
}
}
}
In your Spanish class you have
public class Spanish {
public Spanish() {}
}
but public Spanish() is not an ordinary method, it's a constructor that only can be called with the keyword new which you already do.
if (language.equals("Span")) {
Spanish span = new Spanish();
span.Spanish();
}
(I removed the package name since it isn't needed) So you need another method in your Spanish class that does the actual work.
The main problem though, apart from the fact that you have duplicated all the code, is that you are trying to do everything in the main() method of CashRegister
I would, for a start, create a simple starting class, lets call it Starter that ask the language question and then lets the CashRegister or Spanish class handle the main functionality.
class Starter {
public static void main(String[] args) {
//Ask question about language as before
if (language.equals("Span")) {
Spanish.register();
} else {
CashRegister.register();
}
}
}
And then you implement a register method in both CashRegister and Spanish that contain the code after else, note that I made the method static
public class CashRegister {
public static void register() {
System.out.print("Please enter cash register's float: $");
registerfloat = in.nextLine();
balance = Double.parseDouble(registerfloat);
//... rest of code
}
}
This should get you started but there are many further improvements that can be done.
If you don't want to have a static method the Starter class needs to be modified as below but I think a static method makes more sense.
if (language.equals("Span")) {
Spanish spanish = new Spanish();
spanish.register();
} else {
CashRegister cashRegister = new CashRegister();
cashRegister.register();
}

Why won't the last output line in this program display on NetBeans? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I'm trying to make a simple "store" program with a prompt to exit the program at the end. If the user types yes, it will exit. But if they say no, it's supposed to just print a message to let them know they can keep shopping. For some reason that message doesn't appear though. Here is the object.
public class HelloShopper1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Hello Shopper, what is your name?\n");
String input = scanner.nextLine();
if(!input.matches("[a-zA-Z_]+")) {
System.out.println("Nice try " + input + " . Get out of my store!");
} else {
System.out.println("Thank you, " + input + ". It is my pleasure to help you today.");
System.out.println("Do you want to close this program?");
String input1 = scanner.nextLine();
System.out.println(input1);
if(input1 == "yes") {
System.exit(0);
if(input1 == "no") {
System.out.println("Thank god. Please continue shopping.");
}
}
}
}
import java.util.*;
public class HelloShopper1
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Hello Shopper, what is your name?\n");
String input = scanner.nextLine();
if(!input.matches("[a-zA-Z_]+"))
{
System.out.println("Nice try " + input + " . Get out of my
store!");
}else{
System.out.println("Thank you, " + input + ". It is my pleasure to
help you today.");
System.out.println("Do you want to close this program?");
String input1 = scanner.nextLine();
if(input1.equalsIgnoreCase("yes"))
{
System.exit(0);
}
if(input1.equalsIgnoreCase("no"))
{
System.out.println("Thank god. Please continue shopping.");
}
}
}
}

Having trouble adding a for loop to program

I'm having trouble adding a for loop into my older program. I have to make it so at the end the user has an option to ask the question again. This is what I have so far
Also just started learning for loops sorry if the question is stupid
http://gyazo.com/a71e2a0b06ed41c47d62ccc05d8ffec8
Your question isn't stupid, I think you just have the wrong idea here.
Anyways, here's your code, editable, and copyable
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years: ");
int age = scan.nextInt();
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
}
}
/*
this is the code you had trouble including
for(int age = scan.nextInt(); int dogAge = age * 7; i++);
{
System.out.print("Enter your dog's age in human years: ");
}
*/
Anyways, so that's your code. All you ever need to do is copy paste, and then highlight all the code, then press the 2 brackets symbols in the little box above the text field.
Now, as to your actual question, a simple way to make all this possible would be, throw that for loop around everything that you want the program to repeat (and a method I added in to ensure it's numeric), here is what I mean.
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years. ");
int age = scan.nextInt();
for(int i = 0; i < 10000; i++)
{
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
System.out.print("Enter your dog's age in human years. (Enter a negative number to stop the program)\n");
String response = scan.next();
age = Integer.parseInt(response);
if(age < 0)
{
i = 10001;
}
}
}
}

Categories