I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
Here is part of my program (in the class PressureInput) and where my issues start:
public void setSystolic(int sys)
{
sys = sysAvrg;
}
So, assuming the avrgSys has a number (it does), I then want to pass the info to the other class (BPChecker).
I don't feel like I'm doing this right, or at least, not in such a way as to facilitate passing the 'int' of sysAvrg from the class its in into another class (BPChecker).
I'm not sure whether to use a getSystolic since I'm not sure what the return would be.
I can't just initialize sys in the other class (BPChecker) without giving sys a value (which defeats the purpose), but it keeps telling me to.
In the end, I need to move the number of avrgSys into BPChecker without rewriting the whole program. So far, I keep getting a lot of 0s or errors...
Any help is appreciated, though my newness may have more complicated explanations go over my head (sorry to say).
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
In Object-oriented programming, you can create an instance of an object in any class you want. In order to access class variables from other classes, you can use accessor methods.
i.e.
public class PressureInput {
private static int sysAvrg;
public PressureInput(int sysAvrg){
this.sysAvrg = sysAvrg;
}
public void setSystolic(int sys){
this.sysAvrg = sys;
}
public int getSystolic() {
return this.sysAvrg;
}
}
You have a variable called sys so if you want to set it with the average create a setter Method:
public void setSystAve(float sysAvrgParameter){
sysAvrg = sysAvrgParameter;
}
if you want to get the sysAvrg create a getter Method:
public float getSystAve(){
return sysAvrgParameter;
}
now somewhere in your code:
sys = yourObject.getSystAve();
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I wish to limit the input of an integer value, between certain values using a while loop, with a couple of if-else if-else statements inside it! It's kinda working, but not exactly as it should... thought of using a switch as well, but I'm too "green" to know how! If someone's up for it and knows how... I'd welcome the use of a switch as well! Even a nested switch if need be...
Here's my code:
public class OOPProject {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
Car Honda = new Car(2018, 20000, "Honda", "Civic", 200, 6, 0, 0);
System.out.println("Manufacturer is: " + Honda.maker + ", model: " + Honda.model +
", year of fabrication: " + Honda.year + ", price: " + Honda.price + "!");
System.out.println("Please start the engine of your vehicle, by typing in 'Yes' or 'Start' or 'Turn on'!");
System.out.print("Do you wish to start the engine?");
System.out.println(" ");
Honda.StartEngine(sc);
//System.out.println("Engine is on!");
System.out.println("Do you wish to depart? Shift in to the first gear then and accelerate!");
System.out.println("Type in the speed: ");
Honda.accelerate(sc);
System.out.println("We are departing! Shifting in to " + Honda.currentGear +
"st gear and accelerating to " + Honda.currentSpeed + " km per hour!");
}
Constructor & functions:
public class Car {
public int year;
public int price;
public String maker;
public String model;
public int maximumSpeed;
public int numberOfGears;
public int currentSpeed;
public int currentGear;
public boolean isEngineOn;
public Car(int year, int price, String maker, String model, int maximumSpeed,
int numberOfGears, int currentSpeed, int currentGear) {
this.year = year;
this.price = price;
this.maker = maker;
this.model = model;
this.maximumSpeed = maximumSpeed;
this.numberOfGears = numberOfGears;
this.currentSpeed = currentSpeed;
this.currentGear = currentGear;
}
public String StartEngine(Scanner in) {
while(in.hasNext()) {
String input = in.nextLine();
if(input.equals("Yes") || input.equals("Start") || input.equals("Turn on")) {
isEngineOn = true;
System.out.println("Engine is on!");
return input;
} else {
System.out.println("Your input is not correct! Please start the engine!");
}
}
return null;
}
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(isEngineOn && currentSpeed > 0){
currentGear++;
} else if(currentSpeed > 50){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
It's taking the input, but it's not going further with it as it should, neither does it give an error message or stop the app, what's my mistake?
Changing the order of your if statement will work.
In your current method:
if(isEngineOn && currentSpeed > 0)
Will always return true with any value that you enter.
Using this method will get you a little further, although I suspect it will still won't be what you are expecting, but I hope it helps you in the right direction.
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(currentSpeed > 50 && currentGear <= 1){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else if(isEngineOn && currentSpeed > 0){
currentGear++;
break; /* I've added this to break out of the method to progress in your flow */
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.
I am relatively new to Java. And I am a Student in the second semester.
The following has been my last task, and I have already presented it. Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled.
The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. (e.g. use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player)
So having that said I do not mean for people to solve these task because as you will see they have been completed.
Just one additional thing gives me trouble.
I use a Linked list to store the guessed numbers and recall them when needed.
So finally my question is:
How would I go about switching the Linked list with an Array?
Here the code:
Here the Run Class:
package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
game.setTopNum() // defines the maximum range of numbers
which you want to guess. Starting from 0!
-----------------------------------------------------
*/
public static void main(String[] args){
Game game = new Game(0);
//game.getNumPlayers();
game.setBotPlayers(100);
game.setTopNum(2000);
game.start();
}
}
Game Class:
package fourfive;
import java.util.Random;
import java.util.Scanner;
public class Game {
/*
Some Variables being defined here.
*/
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1
public Game(int numPlayers) {
this(numPlayers, 10);
}
public Game(int numPlayers, int maxTries) {
this(numPlayers, maxTries, 1000);
}
public Game(int numPlayers, int maxTries, int topNum) {
MAX_Tries = maxTries;
TOP_Num = topNum;
this.numPlayers = numPlayers;
resetPlayers();
resetTheNumber();
}
/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
*/
public void resetPlayers() {
players = new Human[numPlayers + numBots];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Human(i + 1);
}
for (int i = numPlayers; i < (numBots + numPlayers); i++) {
players[i] = new Computer(i + 1, TOP_Num);
}
}
public void setNumPlayers(int numPlayers) {
this.numPlayers = numBots;
resetPlayers();
}
public void setBotPlayers(int numBots) {
this.numBots = numBots;
resetPlayers();
}
public int getMaxTries() {
return MAX_Tries;
}
public void setMaxTries(int maxTries) {
this.MAX_Tries = maxTries;
}
public int getTopNum() {
return TOP_Num;
}
public void setTopNum(int topNum) {
this.TOP_Num = topNum;
resetTheNumber();
resetPlayers();
}
private void resetTheNumber() {
num = rand.nextInt(TOP_Num);
}
public void start() {
resetPlayers();
System.out.println("Welcome to the Guess a Number Game!\n");
System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
currentPlayer = players[0];
System.out.println("The num " + num);
/*
Polymorphism example.
Any object that can pore than one IS-A test is considered to be Polymorphic.
In this case we are setting up a condition in which any given player has
the ability to win, which is depicted from the "isCorrect()" Method.
*/
while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
for (int i = 0; i < players.length; i++) {
//currentPlayer = players[i];
players[i].guess();
if (isCorrect()) {
gameWinner = true;
printWinner();
break;
} else
printWrong();
}
if (!gameWinner) {
printTriesLeft();
}
}
if (!gameWinner)
printLoser();
}
public boolean isCorrect() {
return currentPlayer.getLastGuess() == num;
}
public void printWinner() {
if (currentPlayer instanceof Computer)
System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
else
System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}
public void printLoser() {
System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}
public void printWrong() {
String word = "too high";
if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
word = "too low";
System.out.println("Nope! " + word + "!");
}
public void printTriesLeft() {
System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}
public void getNumPlayers() {
System.out.print("Enter number of Persons playing => ");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter the number of Players => ");
}
numPlayers = input.nextInt();
System.out.print("Enter number of Bots! =>");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter number of Bots! =>");
}
numBots = input.nextInt();
resetPlayers();
}
}
Participants class:
package fourfive;
import java.util.LinkedList;
public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
return guesses.peek();
}
public int getPlayerNum(){
return playerNum;
}
public int getNumTries(){
return guesses.size();
}
}
Now the Human class: (basically the human player)
package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
numTries = 0;
this.playerNum = playerNum;
guesses = new LinkedList<Integer>();
}
public void guess(){
System.out.print("Player " + playerNum + "guess =>");
while(!input.hasNextInt()){
input.nextLine();
System.out.println("Invalid input!");
System.out.print("Player " + playerNum + "guess =>");
}
guesses.push(input.nextInt());
}
}
And Last the Computer class:
package fourfive;
import java.util.Random;
public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;
Computer(int playerNum) {
super(playerNum);
maxGuess = 1000;
}
Computer(int playerNum, int topNum){
super(playerNum);
maxGuess = topNum;
}
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
guesses.push(guess);
}
public int getMaxGuess() {
return maxGuess;
}
public void setMaxGuess(int num) {
maxGuess = num;
}
}
You would initialize the Array with a fixed size, e.g. 4 and resize if needed. For this, you need an extra attribute to store the fill level of the array.
int[] guesses = new int[4];
int guessFilling = 0;
[...]
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
if (guessFilling == guesses.length) {
resizeGuesses();
}
guesses[guessFilling++] = guess;
}
private void resizeGuesses() {
int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
guesses = newGuesses;
}
import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.
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!");
}