I'm trying to make a quiz type game and for some reason when I add the if statement below it executes the ask method twice. You will get asked the question twice before it returns whether it is correct or not.
import java.util.Scanner;
public class QuizGame
{
private int correct;
private int wrong;
private Scanner inputScan;
private Quiz customQuiz;
public QuizGame()
{
correct=0;
wrong=0;
inputScan = new Scanner(System.in);
}
private void startQuiz()
{
System.out.println("Use custom upper limit? (y/n) ");
String custom = inputScan.next();
if(custom.equalsIgnoreCase("y"))
{
System.out.println("What do you want to be your upper limit?");
int limit = inputScan.nextInt();
customQuiz = new Quiz(limit);
customQuiz.ask();
if(customQuiz.ask())
{
correct +=1;
System.out.println("Correct!");
}
else
{
wrong+=1;
System.out.println("Wrong!");
}
}
}
public static void main(String[] args)
{
QuizGame quiz1 = new QuizGame();
quiz1.startQuiz();
}
}
other class that asks the questions:
import java.util.Random;
import java.util.Scanner;
public class Quiz
{
private Random rGen;
private int num1;
private int num2;
private Scanner getInput;
private int answer;
public Quiz(int n1)
{
rGen = new Random();
num1 = rGen.nextInt(n1);
num2 = rGen.nextInt(n1);
getInput = new Scanner(System.in);
}
public boolean ask()
{
int answer = num1 * num2;
System.out.println("What is " + num1 + " x " + num2);
int userAnswer = getInput.nextInt();
return answer == userAnswer;
}
}
I isolated the problem and it definitely seems to be the if statement: if(customGame.ask()) {} in the driver class, but I don't see why. It's not like if(customGame.ask()) calls the ask method again, it just tests if it returns true? I've also tried with just if(customGame.ask() == true) and still nothing.
Well, you are calling customQuiz.ask() twice :
customQuiz.ask();
if (customQuiz.ask ())
{
correct += 1;
System.out.println ("Correct!");
}
Simply call it just once :
if (customQuiz.ask ())
{
correct +=1;
System.out.println ("Correct!");
}
Or (as suggested by #RobertHarvey) you can put the result of the method in a variable and use it later :
boolean correct = customQuiz.ask ();
if (correct)
{
correct += 1;
System.out.println ("Correct!");
}
Related
I am trying to build a math Calculator in Java but I am having problems with it, I want to build it with methods and not just int.
I am having problems with how to print the return value (rishon+sheni) and also how to check if the in.nextLine() that the console wrote equal to plus like that:
package mehadash;
import java.util.Scanner;
public class lilmod {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String plus = null;
String minus = null;
String math;
int sum = 0;
System.out.println("What kind of math you want to do?");
math = in.nextLine();
if(math = plus)
{
System.out.println("Enter the two numbers you would like to check");
SumNumbers(in.nextInt(),in.nextInt());
System.out.println("The answer is :" +SumNumbers());
}
minusNumbers(in.nextInt(),in.nextInt());
}
public static int SumNumbers(int rishon , int sheni)
{
return rishon + sheni;
}
public static int minusNumbers(int rishon , int sheni)
{
return rishon - sheni;
}
}
You can always just define more variables.
int numberA = in.nextInt();
int numberB = in.nextInt();
int result = SumNumbers(numberA, numberB);
System.out.println("The result: " + result);
how to print the return value (rishon+sheni)
Try this way:
System.out.println("The answer is :" +SumNumbers(in.nextInt(),in.nextInt()));
instead of
SumNumbers(in.nextInt(),in.nextInt());
System.out.println("The answer is :" +SumNumbers());
also how to check if the in.nextLine(); that the console wrote equal
to plus
Try
if(math.equals("+"))
instead of
if(math = plus)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The goal of this assignment is to generate a multiplication problem in class Multiplier to display in GameTester so that the user may input an answer. If incorrect 3 times, it will display the correct answer and then prompt whether or not they would like to play again. My overall issue is after they solve or fail to solve the problem and I prompt the next question they are unable to answer. I am looking for a more efficient way to display another question so that it is more fluid and continuous in the program.
import java.util.Scanner;
public class GameTester{
public static String question;
public static void main(String[] args){
Multiplier m = new Multiplier();
Scanner s = new Scanner(System.in);
question = m.generateProblem();
System.out.println(question);
int userAnswer = s.nextInt();
if(userAnswer == m.checkAnswer()){
System.out.println("Correct!! Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
else {
System.out.println("Sorry, the answer is incorrect. Try again!");
s.nextLine();
for(int i = 0; i <=1; i++){
System.out.println(question);
if(i != 1 && s.nextInt() != m.checkAnswer()){
System.out.println("Sorry, the answer is incorrect. Try again!");
}
else if(i == 1 && s.nextInt() != m.checkAnswer()){
System.out.println("The correct answer was " + m.checkAnswer());
System.out.println("Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
else{
System.out.println("Correct!! Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
}
}
}
public static void playAgain(String userInput){
if(userInput.equals("yes")){
Multiplier m2 = new Multiplier();
question = m2.generateProblem();
System.out.println(question);
}
else{
System.exit(0);
}
}
}
import java.util.Random;
public class Multiplier{
public static int product;
public Multiplier(){
}
public static String generateProblem(){
Random r = new Random();
int term1 = r.nextInt(11);
int term2 = r.nextInt(11);
product = term1 * term2;
String s = "How much is " + term1 + " times " + term2 + "?";
return s;
}
public static int checkAnswer(){
return product;
}
}
It's all a simple matter of utilizing a boolean flag and while loops at specific locations. By doing this you can actually eliminate the playAgain() method but on the same token, we create other methods to streamline the flow and eliminate duplicate code.
Since you've brought up the subject of flow, it's always a good idea to keep your Class's main() method clean and by clean I mean by only placing relevant code or calls pertaining to to the true flow of your application instead of filling it with what I call method clutter. Allow the main() method to deal with Command Line Arguments and call another method to actually start your application, branching can then go from there. Try to only place method calls that outline the true main flow of your application. Even though your project is a simple console application it's still a good habit to get into if for anything, the sake of readability. Then again...this is just my opinion and really holds no merit to any of the valid answers provided towards your post.
You might want to streamline your code like this:
package gametester;
import java.util.InputMismatchException;
import java.util.Scanner;
public class GameTester {
public static String question;
public static int questionCount = 0;
private static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
playQuiz();
}
private static void playQuiz() {
boolean playAgain = true;
System.out.println("First Question:");
while (playAgain) {
question = Multiplier.generateProblem();
System.out.println(question);
int userAnswer = getAnswer();
playAgain = processAnswer(userAnswer);
}
}
private static int getAnswer() {
int answer = 0;
while (true) {
answer = 0;
// Trap any non-numerical answers from User
try {
answer = s.nextInt();
s.nextLine();
} catch (InputMismatchException ex) {
// Needed to clear the scanner buffer otherwise
// this catch clause will play over and over again
// indefinately.
s.nextLine();
// Display an Input fault to User.
System.err.println("Incorrect Numerical Response Provided "
+ "(Numbers only please)! Try Again.\n");
// Get another answer from User.
continue;
}
break; // Good input, get outta this loop
}
return answer;
}
private static boolean processAnswer(int userAnswer) {
boolean pAgain = false;
if (userAnswer == Multiplier.checkAnswer()) {
System.out.print("Correct!! ");
pAgain = promptPlayAgain();
} else {
System.out.println("Sorry, the answer is incorrect. Try again!");
for (int i = 0; i <= 1; i++) {
System.out.print(question);
System.out.println(" (Attempt #: " + (i+2) + ")");
int ans = getAnswer();
if (i != 1 && ans != Multiplier.checkAnswer()) {
System.out.println("Sorry, the answer is incorrect. Try again!");
} else if (i == 1 && ans != Multiplier.checkAnswer()) {
System.out.println("The correct answer was " + Multiplier.checkAnswer());
pAgain = promptPlayAgain();
} else {
System.out.print("Correct!! ");
pAgain = promptPlayAgain();
break;
}
}
}
return pAgain;
}
private static boolean promptPlayAgain() {
boolean pAgain = false;
while (true) {
System.out.println("Want to play again (y or n)?");
String user = s.nextLine();
if (user.toLowerCase().charAt(0) == 'n') {
pAgain = false;
break;
} else if (user.toLowerCase().charAt(0) == 'y') {
pAgain = true;
System.out.println("\nNext Question :");
break;
} else {
System.err.println("Incorrect Response ('y' or 'n' exprected)! Try Again.\n");
}
}
return pAgain;
}
}
And your Multiplier Class:
package gametester;
import static gametester.GameTester.questionCount;
import java.util.Random;
public class Multiplier{
public static int product;
public Multiplier(){ }
public static String generateProblem(){
questionCount++;
Random r = new Random();
int term1 = r.nextInt(11);
int term2 = r.nextInt(11);
product = term1 * term2;
String s = String.valueOf(questionCount) + ") How much is " + term1 + " times " + term2 + "?";
return s;
}
public static int checkAnswer(){
return product;
}
}
Now, put a configurable time limit on each question :)
You could split the asking of the question into a method askQuestion. This would instantiate a Multiplier, output the question, and take the user's response. Your method askQuestion could either return the Multiplier, or check the answer and return a boolean indicating whether they got it right.
Your main method would then mainly contain the control loop necessary to run the program. One useful tool for repeatedly asking something is a do-while loop, which runs a block of code at least once, and then repeatedly until a condition is satisfied. For example:
boolean Correct = false;
int Attempts = 0;
do {
Correct = askQuestion();
Attempts++;
} while (!Correct && Attempts < 3);
You can use the while loop as:
public static void main(String[] args) {
Multiplier m = new Multiplier();
Scanner s = new Scanner(System.in);
question = m.generateProblem();
System.out.println(question);
String user;
int count = 0;
int userAnswer;
while (true) {
userAnswer = s.nextInt();
if (userAnswer == m.checkAnswer()) {
System.out.println("Correct!! Want to play again?");
s.nextLine();
user = s.nextLine();
playAgain(user);
count = 0;
} else {
if(count == 2){
System.out.println("The correct answer was " + m.checkAnswer());
System.out.println("Want to play again?");
s.nextLine();
user = s.nextLine();
playAgain(user);
count = 0;
} else {
System.out.println("Sorry, the answer is incorrect. Try again!");
count++;
}
}
}
}
I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}
I want my program to execute the first return statement if the conditions are true otherwise return it as normal.
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
return answer;
}
}
Well, in your code you don't need to return anything.
But, if you want to return something you are in the wrong method.
main is a "special" method, it cannot return anything (well, in other languages it might return an int which is the exit status, but ignore it here) and is where your code starts.
If you want to return something you should write a method.
A method is a block of code which is execute when you call it and can return value back to who called it. In this case your method will be static because you will call it from the main method which is static
public static int methodName()
{
int X, Y;
int answer;
if (x == y)
{
// Do something
return returnSomethingBackTomain;
}
else
{
return returnSomethingOfDifferentTomain;
}
}
Well.. it could be your method
public static int methodName()
{
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
}
else {
System.out.println("These two numbers are not the same, but they equal: " + answer);
}
return answer;
}
But please be more specific on what you want to do.
Because i dont see any reason to write a such method.
If your main function is void, you don't have to return anything, you can just use
return;
That gives:
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
But you can also do:
...
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
} else {
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
}
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y)
System.out.println("These two numbers are the same and they equal: " + answer);
else
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
main has a void return type, so no need to return anything.
By the way, try to fit CQS principle.
Indeed, printing something is a side-effect operation, so no need to return anything but void.
You're making a few mistakes.
The main method should never be used to return a value.
The main method is the entry point to your program.
Here you declare methods to be run at the start of the program. In GUI-projects, this is used to load the inital GUI (Forms).
Also, a void method cannot return something.
When initalising a method, you have to declare what type the returned value will have.
Void means that there is no data returned.
You will have to write a method which you can call to receive your data.
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
return answer;
}
Now you can initalize your class (e.g. Scanner) and call the method scanForEqualNumbers.
Scanner scanner = new Scanner();
int result = scanner.scanForEqualNumbers();
If you don't want to have to initialize a class to call the method, you can declare the scanForEqualNumbers as static.
public static int scanForEqualNumbers() { ...
Then you can call this method directly as this:
int result = Scanner.scanForEqualNumbers();
1 more note.
You don't need the return in the IF-statement.
As you return the answer anyway, you can keep the print the the IF-statement and use the return after it.
You could also return -1 as answer in an ELSE-statement so you can use this answer in further methods. This way you can check the result of the method without having to read the console output.
I even suggest to make a seperate class for this.
You'll need your Main-method to run your program. This'll also be the location of your method class.
public class MyApp {
public static void main(String[] args) {
MyScanner myScanner = new MyScanner();
int result = myScanner.scanForEqualNumbers();
System.out.format("The scanned numbers %s equal", result > 0 ? "ARE" : "are NOT");
}
}
public class MyScanner {
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
/* This can be replaced, see below
int answer = x + y;
if (x != y) {
answer = -1;
}
return answer;
*/
// IF X equals Y ? return X + Y : ELSE return -1
return (x == y ? x + y : -1);
}
}
This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}