if statement not working properly with variables from another method - java

I'm totally new to Java (4 days old), and I'm trying to create my first program after watching a few YouTube videos.
Basically I'm trying to make a (guess my number game). I've created a function/method to get a random number and another function/method to get a user inputted number (both from another class called random)
I've then called these 2 values in my main method/function to be compared in a (if) statement but every time I run the program I get the same output.
Output:
Welcome to The Guessing Game
*******Version 1.1**********
Enter your name please :
john
Nice to meet you john
Ok then....let's go over the rules
I'm gonna pick a number between 1 and 10
You have 4 atempts to guess otherwise i win
Good luck!!!!
Ok i've chosen the number between 1 and 10
take a guess :
2
You are correct!!!!
I seem to get the same output every time ;-(
Sorry in advance for asking a maybe straight forward question.
(Do remember I'm a newbie and many thanks for your help.)
shaz
Below is a copy of my code:
public class GuessMain {
public static void main(String[] args) {
introduction intro = new introduction();
intro.welcome();
introduction enterName = new introduction();
enterName.userName();
introduction rules = new introduction();
rules.explainRules();
// introduction getN = introduction();
// getN.getName();
introduction glMessage = new introduction();
glMessage.goodluckMessage();
random pickRandNumber = new random();
pickRandNumber.pickRandom();
random readyMessage = new random();
readyMessage.readysteadyGo();
random guessNumobj = new random();
guessNumobj.getGuessnum();
random getNumobj = new random();
getNumobj.getNumber();
}
if (guessNumobj.getGuessnum() == getNumobj.getNumber()){
System.out.println("You are correct!!!!");
}else if (guessNumobj.getGuessnum() > getNumobj.getNumber()){
System.out.println("Too high!!!!");
}else if (guessNumobj.getGuessnum() < getNumobj.getNumber()){
System.out.println("Too low!!!!");
}
}
}
import java.util.Scanner;
public class introduction {
private String name;
public void welcome() {
System.out.println("Welcome to The Guessing Game");
System.out.println("*******Version 1.1**********");
}
public void userName() {
System.out.println("Enter your name please :");
Scanner userInput = new Scanner(System.in);
name = userInput.nextLine();
System.out.println("Nice to meet you " + name);
}
public void explainRules() {
System.out.println("Ok then....let's go over the rules");
System.out.println("I'm gonna pick a number between 1 and 10");
System.out.println("You have 4 atempts to guess otherwise i win");
}
public String getName() {
return this.name;
}
public void goodluckMessage() {
System.out.println("Good luck!!!! ");
}
}
import java.util.Random;
import java.util.Scanner;
public class random {
private int number;
private int guessNum;
public void pickRandom () {
Random getRandom = new Random();
for (int counter = 1; counter <= 1; counter++) {
number = getRandom.nextInt(10); //this stores the random number[(10){1 to 10}] in (number;) vairiable
}
}
public void readysteadyGo(){
System.out.println("Ok i've chosen the number between 1 and 10");
System.out.println("take a guess :");
Scanner scanOb = new Scanner(System.in);
guessNum = scanOb.nextInt();
}
public int getNumber(){
return this.number;
}
public int getGuessnum(){
return this.guessNum;
}
}

random is a class, and you can have any number of instances (objects) of that class. Each instance contains its own versions of number and guessNum. If you create two new random() objects, object1 and object2, and you do something that assigns to object1.number, and then you look at the value of object2.number, it will not be the value that you assigned to object1.number.
That's the problem with your code. You create one object pickRandNumber, and then call a method that sets pickRandNumber.number. You create another object readyMessage and then call a method that asks for user input and then sets readyMessage.guessNum. Then you create two new objects, and try to get the number and guessNum from the new objects. Those new objects have their own number and guessNum values, which you haven't set to anything--you've set the values of number and guessNum in different objects.
The solution is to rewrite main() to use the right objects. So after
random pickRandNumber = new random();
pickRandNumber.pickRandom();
that will set pickRandNumber.number, and if you want to retrieve that number, use something like:
if (pickRandNumber.getNumber() == ....)

Related

How do i increment static variables in java

I'm very new to java but i have decent experience with c++ and python. So, I'm doing a question in which im required to implement an airplane booking system, which does the following -
1.initialize all seats to not occupied(false)
2.ask for input(eco or first class)
3.check if seat is not occupied
4.if seat is not occupied allocate seat else look for next seat
5.if economy seats are booked out, ask if user wants to bump up to first class
6.if user is negative display msg "next plane is in 3hrs"
but,
package oop;
import java.util.Arrays;
import java.util.Scanner;
public class AirplaneBooking {
private final static int MAX_ECO_SEATS = 5;
private final static int MAX_FIRST_CLASS_SEATS = 3;
private final static boolean[] ECO_SEATS = new boolean[MAX_ECO_SEATS];
private final static boolean[] FIRST_CLASS_SEATS = new boolean[MAX_FIRST_CLASS_SEATS];
private static int current_eco_seat = 0;
private static int current_first_class_seat = 0;
public static void initialilze_seats(boolean[] first_class_seats, boolean[] eco_class_seats){
Arrays.fill(first_class_seats, Boolean.FALSE);
Arrays.fill(eco_class_seats, Boolean.FALSE);
}
public static void display(boolean[] seats){
System.out.print("[");
for(boolean seat : seats){
System.out.print(seat + ",");
}
System.out.println("]");
}
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
public static int user_input() {
Scanner input = new Scanner(System.in);
System.out.print("Enter 1 for Economy class or 2 for First class : ");
int user_seat_prefrence = input.nextInt();
if (user_seat_prefrence == 1){
if(current_eco_seat < MAX_ECO_SEATS){
book_seat(ECO_SEATS, current_eco_seat);
}
else{
System.out.println("Looks like eco seats are full, would you like to book for first class insted(1/0) ?");
Scanner next_input = new Scanner(System.in);
int user_next_seat_prefrence = next_input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
user_seat_prefrence = 2;
}
else{
System.out.println("next flight leaves in 3 hrs");
}
}
}
else if (user_seat_prefrence == 2){
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
}
else {
System.out.println("Enter valid option");
}
return user_seat_prefrence;
}
public static void print_boarding_pass(int user_seat_prefrence){
if (user_seat_prefrence == 1){
System.out.println("eco");
System.out.println(current_eco_seat - 1);
}
else{
System.out.println("first class");
System.out.println(current_first_class_seat - 1);
}
}
public static void main(String args[]){
initialilze_seats(FIRST_CLASS_SEATS, ECO_SEATS);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
while(true){
int user_seat_prefrence = user_input();
print_boarding_pass(user_seat_prefrence);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
System.out.print("book another seat:");
Scanner choice = new Scanner(System.in);
boolean book_another_seat = choice.nextBoolean();
if (book_another_seat == false)
break;
}
}
}
The problem i'm having with this code is if the seats for eco class(for example) are full, the program is supposed to ask if i want to book for first class instead and wait for my input, if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
Also, i use a static variable current_eco_seat and current_first_class_seat to keep track of the current seat being booked, and i pass that static variable to book_seat function, the program then books the seat and increments the current_eco_seat or current_first_class_seat(depending which is passed) so that next seat can be booked in next interation. But the static variable does not get incremented at all.
These are the only problems i have with the program.
Any help is appreciated, thanks
As Java calls methods by value,
Your problem about static is you are passing the value of current_seat to the book_seat method, so changing the value doesn't affect that variable after returning from the method.
To solve it just call the method and do not pass your static vars. It's static, so you have access it from everywhere.
i.e:
public static void book_seat(boolean [] seats){
seats[current_seat] = true;
current_first_class_seat++;
System.out.println(current_seat);
}
Checking Inout stream
Not sure wether your question is related to "static" variables or more related to "How to handle Input Stream?".
Regarding:
if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
You should think about "flushing" the Input Stream before reading again. flush-clear-system-in-stdin-before-reading
Method Parameter usage
On the other hand this method is wrong
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
this command has no affect, but printing an information to the User. The variable you used in the caller "current_eco_seat" will not change at all.
you don't need to insist incrementing the exact variable, just do the following :
make book_seat() to return incremented value
public static int book_seat(boolean [] seats, int current_seat) {
seats[current_seat] = true;
System.out.println(current_seat + 1);
return current_seat + 1;
}
set returned value to current_first_class_seat or current_eco_seat
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
current_first_class_seat = book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
current_eco_seat = book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
Then you can use book_seat() for both eco and first class reservations handling as previously you have intended.

i need to get the total amount of guesses and also the total amount of games played for the guessing game

so this my first time coding and i need a lot of help trying to figure out to get the total amount of guesses and the total amount games played, i dont even know where to start. I can get the code to tell me how many guesses it took to get to the number in one game but not the overall result. Any tips or help?
thank you
import java.util.Scanner;
import java.util.Random;
public class treehouseproject {
//Instruction on how to play the game
public static void instruction() {
System.out.println("this is a guessing game");
System.out.println("you will guess the number");
System.out.println("that i am thinking of");
System.out.println("unitl you guess the correct number");
System.out.println("the number ranges from 0 to 100");
}
//playing a single game
public static void playgame() {
int guessNumber = 0;
int numberGuesses = 0;
int plays = 0;
int max = 100;
int min = 0;
Random randomNum = new Random();
int givenNumber = min + randomNum.nextInt(max);
Scanner scan = new Scanner (System.in);
while(guessNumber != givenNumber){
numberGuesses++;
System.out.println("Guess: " + numberGuesses);
guessNumber = scan.nextInt();
if (guessNumber == givenNumber) {
System.out.println("correct");
System.out.println("you go it right in " + numberGuesses + " guesses");
}
if (guessNumber < givenNumber) {
System.out.println("higher");
}
if (guessNumber > givenNumber){
System.out.println("lower");
}
}
}
//playing muliple games and reporting all end stats
public static void main(String[] args) {
String Answer = "";
instruction();
playgame();
Scanner console = new Scanner(System.in);
System.out.println("do you want to play again?");
Answer = console.nextLine();
boolean keep_playing = true;
while (Answer.equalsIgnoreCase("yes")){
playgame();
System.out.println("do you want to play again?");
Answer = console.nextLine();
}
}
//prints out the stats of the game
public static void results(int plays, int numberGuesses) {
System.out.println("Overall results");
System.out.println("Total amount of guesses = " + numberGuesses);
System.out.println("Total amount of games = " + plays);
}
}
the problem you are encountering actually has a pretty simple solution.
So if you define a variable it as a certain "lifespan" this means that is effectively dies at some point.
Every variable is only "alive" within the parents of its parent.
Example:
public static void main(string args[]){
String s1 = "";
private static void doSomething(){
String s2 = s1;
}
}
The variable s1 is "alive" until the parenthesizes of its parent (main) close, so its also alive within the function and fully usable.
s2 on the other hand is only alive within "doSomething", so it cannot be referenced after its bracket closes.
So moving the initialization of variables to a more "global" level is often very usefull.
You need to move the initialization of the these variables outside of playGame() and to the global level.
numberGuesses
plays

Guessing game using a tester class

I am creating a Guessing game program in java code. I am having an issue with the main class and the tester class running. Any help would be appreciated. The instructions for the game are The computer generates a random # and the user must guess that number in 7 or fewer guesses. If the guesses exceed 7, then the game is over and the user is asked if they want to 'play again?'
Here is my guess class:
import java.util.Random;
public class Guess
{
int computersNumber; // A random number picked by the computer.
int usersGuess = 0; // A number entered by user as a guess.
int guessCount = 0; // Number of guesses the user has made.
Random random = new Random();
int randomNumber = random.nextInt(100);
public Guess(int n)
{
usersGuess = n;
}
public boolean getGuess()
{
boolean isValid = false;
if (isValid)
{
return false;
}
if (usersGuess == computersNumber)
{
return true;
}
return isValid;
}
public boolean isGuessCorrect()
{
return getGuess() == computersNumber;
}
public int getCount()
{
guessCount ++;
return guessCount;
}
boolean playAgain;
}
Tester/main class:
import java.util.Scanner;
public class GuessTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Let's play a game!");
System.out.println();
System.out.println("The computer will generate a number between 0 and 100. You will have up to seven guesses"
+ "to figure out what the number is. Good luck!");
System.out.println();
System.out.print("What is your first guess? ");
int n = in.nextInt();
Guess guess = new Guess(n);
if (guess.getGuess == computersNumber)
{
System.out.println("That's Correct! ");
}
if (getCount == 7)
{
System.out.println("You lose, you didn't get the number in 7 guesses.");
}
System.out.println("Would you like to play again? ");
in.nextBoolean();
System.out.println();
System.out.println("Thanks for playing.");
in.close();
}
}
There are a few things in your code that don't compile. Did you post all your code?
First things first: if you have a class Guess and you want to access its methods, you need to instantiate an Object of that class first:
int n = in.nextInt();
Guess guess = new Guess(n);
Next, in order to actually access a method of guess it is written like this:
if (guess.getGuess() == computersNumber) {
System.out.println("That's Correct! ");
}
However in your example, the variable computersNumber is not defined in the main class but it is a member of the Guess class. Since both the computersNumber and the method getGuess() are part of the Guess class it would be better to actually access them from within that class and do the comparison there. Maybe in a separate method:
public class Guess{
....
public boolean isGuessCorrect(){
return getGuess() == computersNumber;
}
}
Another thing I saw in your Guess class is that you access some boolean variable in getGuess(), which is not defined:
if (!isValid) {
return false;
}
Where does isValid come from? where is it defined?
Edit: a little hint for the road:
You can generate a random number between 0 and 100 like this:
Random random = new Random();
int randomNumber = random.nextInt(100); // this will be a number between 0 and 100
int another = random.nextInt(1000); // you can reuse the random object and generate more numbers

Trying to make a random array that I can call 5 times, and that i can test against a user input

Need some help trying to set up this assignment. I am not to good with arrays, nor setting up methods to be used in the main. I need to make an array of 10 random numbers 1-100, that can be compared to the user input. I only need the comparison true/false to display. Here is what I have.
I get several errors in trying to print, so i haven't even tried to compare it to the user input yet.
Thanks,
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print(shots);
}
public int [] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++)
shots[i] = r.nextInt(100);
return shots;
}
public static void print(int shots[]) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}
As commentors said, please provide error messages.
However, I can pick out several issues just for starters. Let's look at your main method...
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print int [](shots);
}
In this call to the print method, why do you have int [] in there? Are you trying to cast something to an int array? Anyways, that has to come out.
Also, you are passing the print method some shots variable that doesn't exist.
Your print method takes an int array as its only argument, so you have to pass it a valid int array. Perhaps you meant to call getRandomNumbers() and pass the int array that it returns to the print method?
Also, what's with the nested classes you're showing. You have this class Final with another class ShotClass defined inside of it. And your closing brackets are all out of whack.
In short, you need to do as the comments ask and format your code and then work through each individual error message, because you've got a whole lot to fix.
EDIT
I'm not sure if I'm doing you more harm than good by giving you the answer to your homework assignment, but I feel for you so here it is. Please just look very carefully at the exact differences between what you posted in your question and what I show below. There's several mistakes you made, including bad syntax and a misunderstanding of how scope works, and I can't properly explain all the problems without typing several pages, so I hope you can learn from this example instead...
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
int[] shots = getRandomNumbers();
print(shots);
}
public static int[] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++) {
shots[i] = r.nextInt(100);
}
return shots;
}
public static void print(int[] shots) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}//END class

looping, get/set methods, and multiple classes, oh my

I am really struggling with get/set methods. I understand the basic concept - first you set the value then you retrieve it. I am finding it rather difficult to find information about it with the minimal concepts I have already learned. I am on the 6th chapter or my first Java and programming class and it is all online. I created a couple other classes that used set/get methods, but those don't really seem to fit this project.
public class Purchase{
int inv;
double sale;
double tax;
double taxAmount = 0.05;
public int getInv()
{
return inv;
}
public void setInv(int inv)
{
inv = inv;
}
public void setSale(double s)
{
sale = s;
tax = sale * taxAmount;
}
public double getSale()
{
return sale;
}
//display
public void display()
{
System.out.println("Invoice number: " + getInv() + "\nSale amount: $" + getSale() + "\nTax: $" + tax + "\nTotal: $" + (tax + sale));
}
}
import java.util.Scanner;
public class CreatePurchase{
public static void main(String[] args)
{
Purchase one = new Purchase();
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
}
while(inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
sale = input.nextInt();
}
}
}
The CreatePurchase class is not finished, but I compile it and get the below for every variable every time it appears:
CreatePurchase.java:16: error: cannot find symbol
inv = input.nextInt();
^
It was my understanding that a default constructor is made, so I didn't add one, but called it in CreatePurchase.
Any suggestions?
You've failed to declare the variable inv any where, for example...
public static void main(String[] args) {
Purchase one = new Purchase();
// !! Variable must be declared before it can be used !! //
int inv = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
} while (inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
// This will be your next problem...
sale = input.nextInt();
}
}
Your Purchase class is also going to have problems...
The following method is essentially assigning the value of inv back to itself, which is meaningless in this context...
public void setInv(int inv)
{
inv = inv;
}
Instead, you should be assigning to the instance of the Purchase class's inv variable...
public void setInv(int inv)
{
this.inv = inv;
}
You have at least two problems. First, you can create a new variable with the same name as another variable that's in a bigger container (scope). In this case, the new variable "hides" or "shadows" the outer one. In your setInv method, when you say inv = inv, both invs refer to the innermost variable, the one in the method signature. To save the argument to the class's field, you need to specify the outer inv: this.inv = inv;.
In your CreatePurchase class, you don't have any inv defined; there's one in Purchase, but that's over there, not here. You just need to declare int inv; right after your Purchase one.
Based on these two errors, I would recommend reading an article or tutorial about variable scope in Java to learn the rules about which variables are accessible where.
You havent declared the variable inv in main method, at this step
inv = input.nextInt();
Change your program to below
int inv = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
if(inv >1000 & inv <8000)
one.setInv(inv);//add to one variable only if its correct,otherwise ignore it
}
while(inv < 1000 && inv > 8000);

Categories