How do I use loop statement instead of go to statement - java

while(true)
{
switch (...)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
System.out.println("(1)Continue (2)Exit");
//example:
int choice = scanner.nextInt();
if (choice == 1)
continue; //it should go to switch
else if (choice == 2)
{
System.out.println("Exit..."); // should exit
break;
}
else
{
System.out.println("Wrong num, try it again!"); // should ask choose again until we enter 1 or 2
//goto example;
}
}
My problem is: It goes to the beginning of the loop when I choose the wrong number. I want it to go to the part where the choose is asked (int choice = scanner.nextInt();) and asking again. "1" - > switch, "2" - > "exit" , "3" - > ask choice again.

Try like the below
while(true)
{
int choice = scanner.nextInt();
if (choice == 1)
continue;
else if (choice == 2)
{
System.out.println("Exit...");
break;
}
else
{
System.out.println("Wrong num, try it again!");
//goto example;
}
}

This should solve your problem.
import java.util.Scanner;
class Main
{
private static void switcher(int key)
{
switch (key)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
switcher(0);//replace with whatever you need
System.out.println("(1)Continue (2)Exit");
while(true)
{
int choice = sc.nextInt();
if (choice == 1)
continue;
else if (choice == 2)
{
System.out.println("Exit...");
break;
}
else
{
System.out.println("Wrong num, try it again!");
}
switcher(0);//replace with whatever you need
}
}
}
If you have other requirements, please update your question.

You can try doing something like this, maybe a little ugly but I think it will work:
function get_choice(choice) {
if (choice == 1) {
// do something
} else if (choice == 2) {
// do something else
} else {
// something else
}
}
and then you just do something like get_choice(1);

try this approach:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int choice;
do {
System.out.println("Enter your choice :");
System.out.println("1. Start program");
System.out.println("2. End program");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
} while (choice != 2);
System.out.println("Exit application :");
}
}

Related

How to use control statements on a methods? if possible

I don't know how to say
if money(); < 1000 and house(); is == small print your poor
or
if money(); >=1000 and < 5000 and house(); is == to normal to print your ok, your too rich
package ArrayTest;
import java.util.Scanner;
/**
* Created by quwi on 02/12/2017.
*/`enter code here`
public class Happyness {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// house();
// money();
comparison();
}
private static void house() {
// getting user input and using the switch statement to see the size
// of their house
System.out.println("Please enter the size of your house ");
String cap = scanner.next();
switch (cap) {
case "small":
System.out.println("you have a small house it means your poor");
break;
case "normal":
System.out.println("your house normal, it mean your not poor nor rich");
break;
case "large":
System.out.println("your house is big it means your rich");
break;
default:
System.out.println("please choose between: small, normal or large");
break;
}
}
private static void money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
System.out.println("your poor");
} else if (wage >= 1000 && wage < 5000) {
System.out.println("your not poor, your OK");
} else if (wage > 5000) {
System.out.println("your rich, Give me money");
} else {
System.out.println("please enter a number nothing else");
}
}
private static void comparison() {
System.out.println("please enter a number");
int decision = scanner.nextInt();
switch (decision) {
case 1:
money();
break;
case 2:
house();
break;
case 3:
money();
house();
break;
default:
System.out.println("Please choose 1, 2 or 3");
}
}
}
Use return value from both to compare.
private static String money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
return "poor";
} else if (wage >= 1000 && wage < 5000) {
return "ok";
} else if (wage > 5000) {
return "rich";
} else {
//ask for input again or exit, whatever
}
}
Do same for the house(). Then, compare the return values from both in another method.

wrong value in while statement java

Fairly new to coding but I am struggling to find the issue in my code. It is just a class which will run a few other classes and ask if you want to play again or not.
The issue is when you choose the first game and then say n or no to not play again when you play a second game after answering that you would like to play again it goes back to asking what game you would play instead of repeating the game.
public static void arcade() {
Scanner scanner2 = new Scanner(System.in);
String choice;
int game;
boolean finish;
finish = false;
game = 0;
do {
try {
System.out.println(
"Which game would you like to play? \n1. Coin toss\n2. Rock Paper Scissors \n3. Number Game\n4. Exit");
game = scanner2.nextInt();
switch (game) {
case 1:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
coinToss(scanner2);
System.out.println("Would you like to play again?");
choice = scanner2.next();
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
choice = scanner2.next();
}
} while (finish != true);
break;
case 2:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
rockPaperScissors(scanner2);
System.out.println("Would you like to play again?");
choice = scanner2.next();
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
}
} while (finish != true);
break;
case 3:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
numberGame(scanner2);
System.out.println("Would you like to play again?");
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
}
} while (finish != true);
break;
case 4:
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid selection");
}
} catch (java.util.InputMismatchException e) {
System.err.println("Please use numbers");
scanner2.nextLine();
}
} while (game != 4);
scanner2.close();
}
Your forgot to re-initialize every time the finish variable to false:
case 2:
choice = "yes";
do {
finish = false;
...
You should do it for every case. Consider also that in your 3rd switch you also forgot to scan for the input after asking "Would you like to play again?".
Finally try to refactor your code a bit :)

How to validate the selection menu using a loop

Can someone edit my code to make it loop the selection menu. If the choice is not one of the 5 options it will prompt the user to re-enter until it is a valid option. If possible an explanation would be helpful as well. Thanks
Here is my code.
import java.util.*;
public class ShapeLoopValidation
{
public static void main (String [] args)
{
chooseShape();
}
public static void chooseShape()
{
while (true){
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
//while (true) {
if (shapeChoice >= 1 && shapeChoice <=4)
{
if (shapeChoice == 1)
{
circle();
}
else if (shapeChoice == 2)
{
rectangle();
}
else if (shapeChoice == 3)
{
triangle();
}
else if (shapeChoice == 4)
{
return;
}
}
else
{
System.out.print("Error : Choice " + shapeChoice + "Does not exist.");
}
}
class Test {
int a, b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
}
First: take a look at switch
Second: read a bit about do-while loops (they are usually a good fit for this kind of situations).
Now, how I would implement it (but you should really learn how to make a loop in this scenarios):
public static void chooseShape () {
boolean valid = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
switch (shapeChoice) {
valid = true;
case 1:
circle();
break;
case 2:
rectangle();
break;
case 3:
triangle();
break;
case 4:
return;
default:
valid = false;
System.out.println("Error : Choice " + shapeChoice + "Does not exist.");
System.out.println("Please select one that exists.")
}
} while (!valid)
}
Use do-while flow control until EXIT code entered:
int shapeChoice;
do {
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
// then use if-else or switch
} while (shapeChoice != 4);
OR
use break statement to loop break at your code as bellow:
else if (shapeChoice == 4)
{
break;
}

Java - Send user back to the start?

How will I go about restarting the app if the user asks so.
Here is my code:
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
}
else if (restart != 1){
System.out.println("Goodbye..");
}
so if user press 1, the app restarts.. How can i create this?
Your application sounds like a loop, so lets use one.
/* #return true if should restart */
boolean run() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
return true;
}
else if (restart != 1){
System.out.println("Goodbye..");
return false;
}
}
while (run());
But this is Java, so you might as well do it more object oriented.
public class MyRestartable {
private boolean shouldRestart = true;
public void run() {
while(this.shouldRestart) {
start();
}
System.out.println("Goodbye..");
}
boolean start() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
this.shouldRestart = sc.nextInt();
}
}
Oh the joys of object based programming.
void start() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
***start();***
}
else if (restart != 1){
System.out.println("Goodbye..");
}
Use a while loop, and at the point you want to send the user back to the beginning, use the break; command enclosed in an if statement to decide whether the user is sent back or continues.
A simple while loop would work.
public static void Loop(){
Scanner input = new Scanner(System.in);
int loop = 1;
while(loop == 1){
System.out.println("Would you like to restart?");
System.out.println("Press 1 = yes");
System.out.println("Press 2 = no");
loop = input.nextInt();
}
}

Error handling with strings java

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
}

Categories

Resources