Maths Game - returning points in methods - java

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.

Related

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();
}
}

How can I handle input string, during the process of if, else if, else including Integer.parseInt?

I would like to handle this situation about inputting wrong string, but error keeps happening because of the else if argument.
Tried try, catch but don't know how to apply it to this code.
import java.util.Scanner;
public class game
{
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
I expect the result from the else block, but when I input wrong string like "c" or "f" and etc, number format exception error: For input string: "c" (or "f" and etc) happens. Thanks for reading this, and hope you solve this problem.
int check = 0;
try{
check = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println("Wrong input");
continue;
}
If you loop this input processing,if it enters catch,you may take input again or you can do what you want when invalid input is entered.If there is no exception,check is your input value,then you can use it in your if and else-if statements like
if(check>0){
...
}
Before Else blocks, you can parse the input like this:
if (input.equals("q")) {
System.out.print("quit the game.");
return;
}
int parsedInput = 0;
try {
parsedInput = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.print("Error. Please try again.");
return;
}
Then you can write if-else for integer input like below:
if (parsedInput == 0) { ... }
else if (parsedInput >= 2 && parsedInput <= 9) {...}
Last else is not needed because I moved it to catch block.
try this it can handle exception
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
int check_input = Integer.parseInt(input);
if (check_input == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
} else if (check_input >= 2 && check_input <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
} catch (Exception e) {
System.out.print("Error. Please try again.");
}
}
}
You just need to check the user provided input is number or not. Before parsing it.
I have added new isNumberic method which is returning boolean flag depending user's input and verify it.
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
Game game = new Game();
boolean isvalid = game.isNumeric(input);
if (input.equals("q")) {
System.out.print("quit the game.");
}
else if (isvalid && Integer.parseInt(input) == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (isvalid && Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
}
You can't send values like a , b, c etc for
Integer.parseInt(String s)
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
I have try catch block to catch numberformat exception with message to enter valid integer
public static void main(String args[]) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
try {
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
catch (NumberFormatException e ) {
System.out.print("pleae enter Valid integer");
}
It's obvious that you are getting this error because you are calling Integer.parseInt on a string variable which doesn't contain an Integer. What you should be doing is putting a check once you get the input to check if the string contains what you need. Something like below
while (true)
{
// Check that the input is between 0 and 9 or q.
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
// If it is not, ask for input again.
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
// If input is correct, break this look.
break;
}
}
Below is the whole code
public class game
{
public static void main(String[] args)
{
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
while (true)
{
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
break;
}
}
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9)
{
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
Verify input in two separate if/else blocks. Add this code to your "else" statement to catch strings other than "q".
else{
try {
int inputNumber = Integer.parseInt(input);
if(inputNumber == 0) {
// code..
} else if (inputNumber >= 2 && inputNumber <= 9) {
// code..
}
} catch(java.lang.NumberFormatException e) {
System.out.print("Error. Please try again.");
}
}
why don't use try catch?
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
Integer i = Integer.parseInt(input);
}catch (NumberFormatException e){
System.out.print("Error. Please try again.");
return;
}

Adding a loop to my game

I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.

ArrayList If Loop not working properly: JAVA

I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire code.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13" );
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
System.out.println("Better Luck Next Time");
}
}
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
// if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
// full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
return full_name;
}
private static int initGame(Scanner user_input){
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
// this is the buffer that resets if the user types a letter
// instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
return numShuffles;
}

A "Stick Game" program in Java not working correctly?

I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();

Categories