Here is the code:
package classes;
import java.util.*;
public class Introduction {
Scanner Input = new Scanner(System.in);
int classChoose;
boolean repeat = false;
public void Introduction() {
System.out.println("\t===THE QUEST FOR PERSEPOLIS===\tv 1.0\n");
System.out.println("Please choose a class: ");
System.out.print("(1)Elite Knight\t");
System.out.print("(2)Dawnguard\n");
System.out.print("(3)Archer\t\t\t");
System.out.print("(4)Barbarian\n");
System.out.print("(5)Mage\t\t\t");
System.out.print("(6)Swordsman\n");
System.out.println("(7)Crossbowman\t");
do {
try {
repeat = false;
classChoose = Input.nextInt();
while(classChoose < 1 || classChoose > 7) {
repeat = false;
System.out.println("Error. Enter a number between 1 and 7(inclusive).");
classChoose = Input.nextInt();
}
}
catch(InputMismatchException e) {
repeat = true;
System.err.println("Caught: "+e);
Input.nextLine();
}
}while(repeat = true);
switch(classChoose) {
case 1: chooseKnight();
break;
case 2: chooseGuard();
break;
case 3: chooseArcher();
break;
case 4: chooseBarbarian();
break;
case 5: chooseMage();
break;
case 6: chooseSwordsman();
break;
case 7: chooseCrossbowman();
break;
}
}
public static void chooseKnight() {
System.out.println("You have chosen the Elite Knight. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseGuard() {
System.out.println("You have chosen the Dawnguard. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseArcher() {
System.out.println("You have chosen the Archer. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseBarbarian() {
System.out.println("You have chosen the Barbarian. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseMage() {
System.out.println("You have chosen the Mage. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseSwordsman() {
System.out.println("You have chosen the Swordsman. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseCrossbowman() {
System.out.println("You have chosen the Crossbowman. You will be briefed and then you shall be set "
+"on your quest!");
}
}
Everytime I run it, the program prompts me to choose my class. After I enter my choice, the program does not go on to the switch statement below the do loop. Can someone help me fix this?
-Calvin
This is an assignment:
while(repeat = true); // Note single '=', not '=='
and the result of which will always be true, from section 15.26 Assignment Operators of the Java Language Specification:
At run time, the result of the assignment expression is the value of the variable
after the assignment has occurred.
Change to:
while(repeat);
while(repeat = true);
should be: -
while(repeat == true); // Or better: - while(repeat);
And in your catch, change Input.nextLine() to Input.next() : -
catch(InputMismatchException e) {
repeat = true;
System.err.println("Caught: "+e);
Input.nextLine(); // Change to Input.next()
}
And your instance variable should begin with a lowercase alphabet or an underscore.. So change Input to input.
Related
If a user answers "yes" one of the 4 quotes print, randomly generate a number between 1 out of 4 and not print it, if a user answers "no" it prints "No quotes " and if it's neither it prints "Invalid", Should i use switch? if/else?
This is Java.
public static void main(String[] args) {
Scanner keyedInput = new Scanner(System.in);
String answer;
System.out.println("Do you want to be inspired? (Enter Yes/No)");
var Gen = Math.floor(Math.random() * 4 + 1);
answer = keyedInput.nextLine();
if (answer.equals("Yes")) {
System.out.println("Quote1");
}
else if (answer.equals("Yes")) {
System.out.println("Quote2");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
if (answer.equals("No")) {
System.out.println("No quotes");
}
else {
System.out.println("Invalid");
}
}
This is a complex task: You want to ask the user yes/no, then if they answer neither 'yes' nor 'no', print something indicating that it's not valid and ask again.
So, make a method! And this method should loop - after all, it needs to keep doing the same thing, over and over again, until the user manages to provide a valid answer.
As a side-note, never use .nextLine(), it doesn't do what you think it does. Only use .next() if you want a string, .nextInt() if you want an int, etcetera. If you want whole lines of input (and you usually do), after making your scanner configure it to read lines at a time with scanner.useDelimiter("\\R");
public static boolean askBoolean(String prompt, Scanner scanner) {
while (true) {
System.out.print(prompt + " (yes/no): ");
String answer = scanner.next();
if (answer.equalsIgnoreCase("Yes")) return true;
if (answer.equalsIgnoreCase("No")) return false;
System.out.println("Please enter yes or no.");
}
}
Let's not use a switch, because equalsIgnoreCase sounds useful here.
and to use:
boolean wantsToBeInspired = askBoolean("Do you want to be inspired?", scanner);
if (wantsToBeInspired) {
showAQuote();
} else {
System.out.println("No quote for you");
}
I believe this is what you are trying to achieve:
int Gen = Math.floor(Math.random() * 4) + 1;
if(answer.equals("Yes")){
switch(Gen){
case 1: System.out.println("Quote 1"); break;
case 2: System.out.println("Quote 2"); break;
case 3: System.out.println("Quote 3"); break;
case 4: System.out.println("Quote 4"); break;
}
}else if(answer.equals("No")){
System.out.println("No quotes");
}else{
System.out.println("Invalid");
}
my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.
How do I switch the order of the outcome? I would liked to be asked to enter output after the menu.
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
Enter a choice: 1
However, I am made to enter input first, and I see:
Enter a choice: 1
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
This is my code:
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
private char readChoice() {
return In.nextChar();
}
private String view() {
return "";
}
private String show() {
return "";
}
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show."); }
Just add help() on top of the use() method:
public void use() {
help();
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
You also need to change 1 and 2 into '1' and '2' respectively, because you are switching over a char. The fact that this compiles is because the compiler applies a narrowing primitive conversion to convert int to char.
I think there are three reasons that the code does not do what you expect.
You are made to enter input first, because before printing anything on the console, the readChoice() function is called. Which waits until it reads one character from the console and then returns. So you must call Help() function once before the while loop.
I guess the switch-case will not do what you expect. I mean the view() and show() functions are not called when you enter 1 or 2. The reason is that you read 1 and 2 as characters not integers. So the switch-case should change to this:
switch (choice) {
case '1': view(); break; //1 changed to '1'
case '2': show(); break; //2 changed to '2'
default: help(); break;
}
I think you might have forgotten to print "Enter a choice:" before reading the character. (I used System.out.print() rather than System.out.println() because it seems that "Enter a choice:" and the choice entered should be in the same line)
private char readChoice() {
System.out.print("Enter a choice:");
return In.nextChar();
}
this is the entire code, hope it works correctly (I put comments so you see what changes I made):
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
help();//called help() once before the loop
while ((choice = readChoice()) != 'X') {
switch (choice) { //cases changed
case '1': view(); break;
case '2': show(); break;
default: help(); break;
}
}
}
private char readChoice() {
//printing "Enter a choice:"
System.out.print("Enter a choice: ");
//I used Scanner class to read the next char, because I don't have 'In' class to use.
//you might write "return In.nextChar();" insead of the following lines
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
return c;
}
private String view() {
System.out.println("you selected view"); //to see this function is called
return "";
}
private String show() {
System.out.println("you selected show"); //to see this function is called
return "";
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show.");
}
};
I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}
my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.