How to use a loop into another loop in Java - java

I am trying to make a small game:
There are 2 heroes you can choose: 1 Warrior and 2 Mage.
Next, you should choose how to travel: 1 by Horse 2 Teleportation (available to Mage only).
Finally, choose a weapon: 1 Sword 2 Staff (*Mage can only use Staff; Warrior can use both).
I created a loop for my first question (choosing a hero) so that if the user enters something else aside from 1 or 2, the program will repeat the question ("Choose your hero: ...). I need the same done for my second and third question (especially since there are some restrictions, e. g. if the user chose Warrior, he can't choose Teleportation as his travel option).
public static void main(String[] args) {
int hero, travel, weapon;
Scanner scan = new Scanner(System.in);
loop:
while (true) {
System.out.println("Choose your hero: 1 for Warrior, 2 for Mage");
hero = scan.nextInt();
switch (hero) {
case 1:
System.out.println("Choose your travel option: 1 for Horse; 2 for Teleportation");
travel = scan.nextInt();
break loop;
case 2:
System.out.println("Choose your travel option: 1 for Horse; 2 for Teleportation");
travel = scan.nextInt();
break loop;
default:
break;
}
}
}
I don't know how to use a loop inside another loop properly. I've tried several options but it always returns an error.

It is always a good idea to split things up, instead of making nested loops. Here is a simple way to split the program in 3 methods, each one dealing with a choice.
Hero choice: Offer both choices and loop until given a valid answer. Then return the answer
private static int queryHero() {
Scanner scan = new Scanner(System.in);
int hero;
while (true) {
System.out.println("Choose your hero: 1 for Warrior, 2 for Mage");
hero = scan.nextInt();
if(hero == 1 || hero == 2) {
break;
} else {
System.out.println(hero + " is not a valid choice");
}
}
return hero;
}
Travel option choice: Offer choices depending on the chosen hero and loop until given a valid answer. Then return the answer
private static int queryTravelOptionForHero(int hero) {
Scanner scan = new Scanner(System.in);
int travelOption;
while (true) {
if (hero == 1) {
System.out.println("Choose your travel option: 1 for Horse");
travelOption = scan.nextInt();
if (travelOption == 1) {
break;
} else {
System.out.println(travelOption + " is not a valid choice");
}
} else if (hero == 2) {
System.out.println("Choose your travel option: 1 for Horse; 2 for Teleportation");
travelOption = scan.nextInt();
if (travelOption == 1 || travelOption == 2) {
break;
} else {
System.out.println(travelOption + " is not a valid choice");
}
}
}
return travelOption;
}
Weapon choice: Offer choices depending on the chosen hero and loop until given a valid answer. Then return the answer
private static int queryWeaponForHero(int hero) {
Scanner scan = new Scanner(System.in);
int weapon;
while (true) {
if(hero == 1) {
System.out.println("Choose your weapon: 1 for Sword; 2 for Staff");
weapon = scan.nextInt();
if (weapon == 1 || weapon == 2) {
break;
} else {
System.out.println(weapon + " is not a valid choice");
}
} else if(hero == 2) {
System.out.println("Choose your weapon: 2 for Staff");
weapon = scan.nextInt();
if(weapon == 2) {
break;
}else {
System.out.println(weapon + " is not a valid choice");
}
}
}
return weapon;
}
Then in your main:
int hero = queryHero();
int travelOption = queryTravelOptionForHero(hero);
int weapon = queryWeaponForHero(hero);
System.out.println("hero: " + hero);
System.out.println("travelOption: " + travelOption);
System.out.println("weapon: " + weapon);
Note: I am not sure if you know about them, but there are ways to make this code nicer using enums and Lists

Your flow can be written as a simple procedural code. As so, I would write it in the most simple form I can - at least as a start.
There is no real justification for using switch labels and loops inside loops
Just write 3 simple loops, one after another - It will be simple to read, understand and debug.
I dont want to write the code for you, it is not the purpose of this site, but here's a Pseudo code:
Loop 1 (selecting heroes)
If(heroes != Warrior)
Loop 2 (selecting travel)
else travel=Horse
Loop 3 (selecing weapon)

Like the comments suggest i would not go with loops inside loops. Instead you should assign the variables one at the time. I have written a helper method selectVariable(String description, String varOne, String varTwo) that you can use to assign variables and give you a start for your story game. You could expand it if you want to give the user more choices. Also don't give the use the illusion a choice can be made, if there is no choice in that situation.
Here is the code that should do what you want:
import java.util.Scanner;
public class Story {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int hero = chooseHero();
int travel = chooseTravel(hero);
int weapon = chooseWeapon(hero);
//For printing purposes give your choice their respective string name again.
String heroDesc = hero == 1 ? "Warrior" : "Mage";
String travelDesc = travel == 1 ? "Horse" : "Teleportation";
String weaponDesc = weapon == 1 ? "Sword" : "Staff";
System.out.printf("you are a %s, traveling by %s, wielding a %s" + System.lineSeparator(), heroDesc, travelDesc, weaponDesc);
}
private static int chooseHero() {
return selectVariable("choose your hero class", "warrior", "mage");
}
private static int chooseTravel(int hero) {
if (hero == 1) { // if the user has no choice don't give the illusion a choice can be made
System.out.println("you are a Warrior you will travel by horse");
return 1;
} else {
return selectVariable("choose your way of travel", "by horse", "teleportation");
}
}
private static int chooseWeapon(int hero) {
if (hero == 2) {
System.out.println("you are a mage you will wield a staff");
return 2;
} else {
return selectVariable("choose your weapon", "sword", "staff");
}
}
//you can reuse this method to also assign other traits to your story
private static int selectVariable(String description, String varOne, String varTwo) {
int var;
do {
System.out.printf("%s: 1 %s, 2 for %s" + System.lineSeparator(), description, varOne, varTwo);
var = scan.nextInt();
switch (var) {
case 1:
System.out.printf("you have chosen %s" + System.lineSeparator(), varOne);
return var;
case 2:
System.out.printf("you have chosen %s" + System.lineSeparator(), varTwo);
return var;
default:
System.out.println(var + " is an invalid choice");
}
}
while (true);
}
}

Related

I have a problem with do while loop in my project

This is the program, I designed it to be a phone store, and the problem I am facing is that after you choose to go back, the program will go back normally, but after you choose to buy the next time it restarts the program. What I want is to make it stop at buy directly.
import java.util.Scanner;
public class MyStore {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Phones phOne = new Phones("iPhone 13.");
phOne.phs(256);
phOne.php(904);
Phones phTwo = new Phones("Galaxy s22.");
phTwo.phs(512);
phTwo.php(1199);
Phones phThree = new Phones("Huawei p50 pocket.");
phThree.phs(512);
phThree.php(1699);
System.out.println("Welcom To My Store!\n-------*****-------");
int i = 1;
do {
System.out.println("Choose a phone please:");
System.out.println("1-iPhone 13.\n2-Galaxy s22.\n3-Huawei p50 pocket.");
int a = scan.nextInt();
System.out.println("-------*****-------");
switch(a) {
case 1:
phOne.print();
System.out.println("1-buy.\n2-go back.");
int bg1 = scan.nextInt();
if(bg1 == 1) {
System.out.println("Congratulations! we will deliver it to you.");
--i;
}
else if(bg1 == 2){
++i;
}
else {
System.out.println("Please choose 1 or 2.");
}
break;
case 2:
phTwo.print();
System.out.println("1-buy.\n2-go back.");
int bg2 = scan.nextInt();
if(bg2 == 1) {
System.out.println("Congratulations! we will deliver it to you.");
--i;
}
else if(bg2 == 2){
++i;
}
else {
System.out.println("Please choose 1 or 2.");
}
break;
case 3:
phThree.print();
System.out.println("1-buy.\n2-go back.");
int bg3 = scan.nextInt();
if(bg3 == 1) {
System.out.println("Congratulations! we will deliver it to you.");
i-=2;
}
else if(bg3 == 2){
++i;
}
else {
System.out.println("Please choose 1 or 2.");
}
break;
default:
System.out.println("Please choose 1, 2, or 3.");
}
}while(i >= 1);
}
}
And this is the rest of the program if you need it.
import java.text.NumberFormat;
public class Phones {
NumberFormat nf = NumberFormat.getCurrencyInstance();
String name;
int storage;
double price;
public Phones(String name) {
this.name = name;
}
public void phs(int phs) {
storage = phs;
}
public void php(double php) {
price = php;
}
public void print() {
System.out.println("Model: "+name);
System.out.println("Storage: "+storage+"G");
System.out.println("Price: "+nf.format(price));
}
}
If you want the program to stop after buying a phone you'd want to implement the do-while loop with a boolean value, then after the user buys a phone set the boolean value to false.
boolean loop = true;
do {
System.out.println("Choose a phone please:");
System.out.println("1-iPhone 13.\n2-Galaxy s22.\n3-Huawei p50 pocket.");
int a = scan.nextInt();
System.out.println("-------*****-------");
switch(a) {
case 1:
phOne.print();
System.out.println("1-buy.\n2-go back.");
int bg1 = scan.nextInt();
if(bg1 == 1) {
System.out.println("Congratulations! we will deliver it to you.");
loop = false;
}
......
while(loop);
I'd recommend taking better care of your variable names. Make them obvious and meaningful, makes it easier to debug in the end!

Newbie to Java trying to figure out how to jump BACK in a do-while loop if a certain input is given

This is the code I have at the moment and I am trying to figure out how to jump back up from case "A" to the top of the do-while loop to allow the user to selection another action. The idea is that the user would be able to check their balance and then go back after checking their balance and either top-up their card or buy a wash. I only know how to end the loop from this point, not how to jump backwards to the previous input.
do {
System.out.println("Please select an option:\nPress [A] to CHECK FUNDS, press [B] to TOP-UP CARD, press [C] to BUY WASH or press [Q] to quit.");
String actionSelection = scan.nextLine();
switch (actionSelection) { //I haven't defined all the cases yet! //The other cases should not need to refer to other classes, all the actions are within the WashCard
case "A":
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
sentinel = true;
System.out.println("Would you like to do something else? Press [B] to go back or [Q] to quit.");
break;
case "B":
System.out.println("How much would you like to deposit?\nPlease type in a number between 200 and 1000.");
//user input
break;
case "C":
//any selection should display card balance
//insufficient funds conditional statement:
if (this.cardBalance < 50) {
sentinel = true;
System.out.println("Not enough credit! Please top-up your card first");
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
}
//only 50 DKK left on the card:
else if (this.cardBalance == 50) {
sentinel = false;
System.out.println("You only have enough credit for the ECONOMY WASH.");
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
}
//any other choice:
else {
sentinel = false;
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
}
break;
default:
sentinel = true;
System.out.println("Please enter a valid input!");
}
} while ( sentinel == true );
You do not need this. This soulution breaks OOP pricniples. To solve it you should encapsulate different logic in different methods.
public class Foo {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
proceed(scan);
}
private static final char CHECK_FUNDS = 'A';
private static final char TOP_UP_CARD = 'B';
private static final char BUY_WASH = 'C';
private static final char QUIT = 'Q';
public static void proceed(Scanner scan) {
while (true) {
System.out.println("Please select an option:");
System.out.format("[%s] - CHECK FUNDS\n", CHECK_FUNDS);
System.out.format("[%s] - TOP-UP CARD\n", TOP_UP_CARD);
System.out.format("[%s] - BUY WASH\n", BUY_WASH);
System.out.format("[%s] - quit\n", QUIT);
System.out.print("> ");
String menu = scan.nextLine().toUpperCase();
char ch = menu.length() == 1 ? menu.charAt(0) : '\0';
if (ch == CHECK_FUNDS)
onCheckFunds();
else if (ch == TOP_UP_CARD)
onTopUpCard();
else if (ch == BUY_WASH)
onBuyWash();
else if (ch == QUIT)
return;
System.err.println("incorrect input");
}
}
private static void onCheckFunds() {
System.out.println("onCheckFunds");
}
private static void onTopUpCard() {
System.out.println("onCheckFunds");
}
private static void onBuyWash() {
System.out.println("onBuyWash");
}
}

How would I loop my program back to the beginning after a question was answered correctly 3 times in a row/ and add variance

I'm creating a program to help with students solving y= m(x) + b. As of right now, I have the program to display the menu and evaluate if your response is correct to the answer. However, I need it to also count the number of correct answers in a row.
If 3 correct end program and output total correct out of attempts tried.
else if there were 3 attempts made the output a tip.
The main issue I'm having is the loop of the two (methods?). I apologize in advance if my code is atrocious, I'm having a hard time understanding methods and classes in this compared to how Python is. Anyone's suggestions or tips would be immensely helpful.
So far I've tried adding methods, and attempts at classes to certain parts of the program such as
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {}
and
public static test_input() {}
However, now I'm facing scoping problems as well as errors referencing certain variables.
package algebra_Tutor;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] args){
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Asks for user input
System.out.print("Enter your selection: ");
}
//Creates random # for values in formula
int y_ = point_of_line_cross;
int m_ = slope;
int b_ = y_intercept;
int x_ = independent_variable;
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
//Converts user input to an integer
int selection = user_Selection.nextInt();
user_Selection.close();
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " +slope +"("+independent_variable+")"+" + "+y_intercept);
System.out.println("Input your answer: ");
}
else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = "+"("+point_of_line_cross+" - "+y_intercept+")"+" / "+independent_variable);
System.out.println("Input your answer: ");
}
else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = "+point_of_line_cross+" - "+slope+"("+independent_variable+")");
System.out.println("Input your answer: ");
}
else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
return;
}
}
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m =(y_) - ((b_) / (x_));
int answer_b =(y_) - ((m_)* (x_));
public static test_input() {
//Problem solver defined
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
//Creates loop for program
var counter = 0;
int correct = 0;
var answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y){
counter++;
correct++;
System.out.println("You answered correctly");
return;
}
else if (counter >= 3 && correct < 3) {
System.out.println("Youve been missing the questions lately, let me help! ");
}
else
{
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
}
I expect the program to output correct answers out of attempts after the user completes 3 problems in a row. In addition, it needs to output a tip after 3 attempts. And then after 3 correct, it should loop back to the beginning of program.
well I figured I would let you figure out how to make it loop on your own but I solved your other problems and put comments where I changed things. Hope this helps
//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;
public static void main(String[] args) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Converts user input to an integer
int selection = user_Selection.nextInt();
//call user_input()
user_input(selection);
}
public static void user_input(int selection) {
Scanner user_Selection = new Scanner(System.in);
int userAnswer;
int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
int slope = (int) Math.floor(Math.random() * 201) - 100;
int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
int independent_variable = (int) Math.floor(Math.random() * 201) - 100;
y_ = point_of_line_cross;
m_ = slope;
b_ = y_intercept;
x_ = independent_variable;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
}
}
// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m = (y_) - ((b_) / (x_));
int answer_b = (y_) - ((m_) * (x_));
//Problem solver defined
int answer = entered_answer;
//Creates loop for program
int counter = 0;
int correct = 0;
boolean answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y) {
counter++;
correct++;
System.out.println("You answered correctly");
return;
} else if (counter >= 3 && correct < 3) {
System.out.println("You've been missing the questions lately, let me help! ");
} else {
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
`
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)
If you give a method parameters, then when the method is called you will have to enter the values into the parameter yourself. I don't think this is what you intended because you defined what you wanted those parameter values to be here:
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
In your test_input() method you wrote:
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
.nextInt() will make the program halt and wait for user input so you don't want to use it until you are ready to get the input.
I don't really know much about the var keyword in java but rather than using var I figured you should just declare the variable type so from this:
var counter = 0;
to this:
int counter = 0;
and to get a better understanding on how methods work I recommend these two videos:
Intro to java methods
Java method parameters and return types
For an in depth explanation of the fundamentals of java in general then I recommend this whole playlist
Java Beginner Programming
It's quite late on a saturday for me to do algebra, so I will stick to suggesting changes to the structure of your program. First, you can accomplish everything with a single class to contain the questions, and score for the user. The methods in that class can be chosen via a menu in the main.
I wrote a sample of how I would structure this based on standard Java OOP methodology. In my program, the main needs no static class, it loops a menu, and the choice of a question is made there. My methods hava single question, you can add as many as you like in the menu, the important thing is the structure.
import java.util.Scanner;
//This class contains the two methods and over-all score
class Material {
private int score;
//The user chooses this or the earth method
public void sky() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
//within the method, is this while loop which gives a hint after 3 attempts.
while (!answer.equals("blue") && (!answer.equals("exit"))) {
System.out.println("What color is the sky? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'b'");
}
if (answer.equals("blue"))
score += 1;//The score will increment if the choice is correct,
else//or else leave with nothing...
return;
}
//This method is the same as the sky() method, just different question and answer.
public void earth() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
while (!answer.equals("iron") && (!answer.equals("exit"))) {
System.out.println("What is the core made of? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'i'");
}
if (answer.equals("iron"))
score += 1;
else
return;
}
public int getScore() {
return score;
}
}
public class Questions {
public static void main(String[] args) {
//No static methods needed, here is an instance of our test materia class.
Material material = new Material();
//The choice and scanner are instantiated here.
int choice = 0;
Scanner input = new Scanner(System.in);
//This while loop uses a switch statement to choose the methods for the questions
while (choice != 3) {
if (material.getScore() == 3) {
System.out.println("Good job, you scored three right.");
return;
}
System.out.println("SCORE: " + material.getScore());
System.out.println("Anwer questions about the sky: 1");
System.out.println("Answer quetions about the earth: 2");
System.out.println("Exit: 3");
choice = input.nextInt();
//choices are 1 , 2 for questions, and 3 to leave.
switch (choice) {
case 1:
material.sky();
break;
case 2:
material.earth();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("not a valid number choice...");
}
}
}// main
}// class
Side note: instead of asking the user for 1, 2, 3 or 4, you should directly ask them to enter the variable they want to solve:
Solve the equation y = m * x + b for which variable (y, m, b, quit)?
This makes the users of the program think more in the problem domain instead of some technically useless indirection.
As you have a Python background you should know that the indentation of the lines is important and has meaning. It's the same for Java programs. The only difference is that the Java compiler ignores the indentation completely. But Java programs are also read by humans, and for them the indentation is viable for understanding the structure of the program. The code you posted has inconsistent indentation, and you should let your IDE fix that.
Your program should be structured like this:
public class AlgebraTutor {
private final Scanner in = new Scanner(System.in);
private final PrintStream out = System.out;
private int attempts = 0;
void solveForY() {
...
}
void solveForM() {
...
}
void solveForB() {
...
}
void mainMenu() {
while (true) {
out.println("Solve the equation y = m * x + b for which variable (y, m, b), or quit?");
if (!in.hasNextLine()) {
return;
}
switch (in.nextLine()) {
case "y":
solveForY();
break;
case "m":
solveForX();
break;
case "b":
solveForB();
break;
case "q":
case "quit":
return;
}
}
}
public static void main(String[] args) {
new AlgebraTutor().mainLoop();
}
}

Java rock paper scissor printing the statements oddly

So here i am trying to create a program that takes an input as an int and then plays a game of Rock paper scissors. It seems to want to reprint statements that it shouldn't be and is skipping printing statements as well. I would love some assistance if possible. I have tried setting up print statements everywhere but it has just been more confusing.
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
System.out.println("Lets play rock paper scissors");
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
//
String answer = "";
while (!a
nswer.equals("No") && (!answer.equals("no"))){
userHand = userHand();
computerHand = computerHand();
System.out.println("The User picks " + userHand + " " );
System.out.print("The Computer picks " + computerHand );
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.println("play again?");
answer = tnt.next();
}
//Condition for the do-while loop
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println(" ");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to userChoice
}
public static String computerHand() //method for computer generated choice
{
int computernum = 1 + (int)(Math.random() * (( 2) +1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "Rock";
}
else if(num == 2){
choice = "Paper";
}
else if(num == 3){
choice = "Scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer wins");
return winner;
}
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
return winner;
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
return winner;
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
return winner;
}
else if(userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
return " ";
}
else{
return winner;
}
}
}
The first problem is that userhand() and computerHand() are being called twice per "round", once at the beginning of the while loop inside the main method and once at the beginning of the getWinner() method. Elimination of the calls at the beginning of the getWinner() method should solve the repeats.
The 2nd Problem is that instead of modifying the value of winner inside the getWinner() method before returning it, you are you are simply outputting the message via println(). an example of fixing this would be converting this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper"){
System.out.println("The computer wins");
return winner;
}
to this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
winner = "The computer wins";
return winner;
}
another minor issue is the fact that
userChoice.equals("Rock") && computerChoice.equals("Paper")
is checked twice, id just remove the entire if else block based around the
2nd check of it
Lastly i would treat the final else clause as the player wins one and set winner to something like " The player wins "

Maths Game - returning points in methods

So my objective is to create a maths game where the user selects if he/she wants a maths question from a file or a random generate one consisting of the 4 maths elements in 3 difficulties.I have created a lot of methods... I have an idea where im going but now im stuck. I need to have it so it keeps a score of questions answered correctly. How do i return the points to the main method and have the game going until the user presses 3 on the gamePlay()method
public class MathsGameProject2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int score;
int points = 0;
int questionType;
System.out.print("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
questionType = keyboard.nextInt();
while (questionType != 3) {
if (questionType == 1) {
questionFromFile();
} else if (questionType == 2) {
randomQuestion();
} else {
System.out.println("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
}
}
}
public static questionFromFile() {
}
public static randomQuestion() {
Scanner keyboard = new Scanner(System.in);
int difficulty;
System.out.println("Please enter the difficulty you want to play." + "\n 1. Easy" + "\n 2. Medium" + "\n 3. Hard\n");
difficulty = keyboard.nextInt();
if (difficulty == 1) {
easy();
} else if (difficulty == 2) {
medium();
} else if (difficulty == 3) {
hard();
} else {
System.out.println("Please enter a number between 1-3\n");
}
}
public static easy() {
Scanner keyboard = new Scanner(System.in);
int mathElement;
System.out.print("What element of maths do you want?" + "\n1 Additon" + "\n2 Subtraction" + "\n3 Multiplication" + "\n4 Division\n");
mathElement = keyboard.nextInt();
if (mathElement == 1) {
easyAdd();
} else if (mathElement == 2) {
easySub();
} else if (mathElement == 3) {
easyMulti();
} else if (mathElement == 4) {
easyDiv();
} else {
System.out.println("Please enter a number between 1-4\n");
}
}
public static easyAdd() {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(10) + 1;
int num2 = rand.nextInt(10) + 1;
int correct = num + num2;
int answer;
System.out.print("What is the answer of " + num + " + " + num2 + " ?");
answer = keyboard.nextInt();
if (answer == correct) {
}
}
In order to keep track of how many questions the user answers successfully, you will need to:
For each question, return whether or not the user answered correctly
Have a counter which increments whenever a user answers a question correctly
Optionally, have a counter which increments whenever a question is answered wrong
For #1, you can use a boolean return value for specifying if the question was answered successfully.
return (answer == correct);
You will want to propagate that return value all the way up to the main() method.
static void main() {
....
boolean isCorrect = randomQuestion();
....
}
static boolean randomQuestion() {
....
return easy();
....
}
static boolean easy() {
....
return easyAdd();
....
}
static boolean easyAdd() {
...
return (answer == correct);
}
Then for #2 and #3, you can increment counter(s) defined in main based on the value returned by randomQuestion()
int numberCorrect = 0;
int numberWrong = 0;
....
boolean isCorrect = randomQuestion();
if (isCorrect) {
numberCorrect++;
} else {
numberIncorrect++;
}
Additionally (no pun intended), you can use a while loop to continuously receive user input until you get your exit code, which in this case is 3. One way to do this is to use a while(true) loop and break out when the user enters 3.
while (true) {
/* Get user input */
....
if (questionType == 3) {
break;
}
}
Finally, after your loop, you can simply print out the value of your numberCorrect and numberIncorrect counters.
Hope this helps.

Categories