How do i increment static variables in java - 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.

Related

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

I have one variable but Java considers them as two

I have initiated the variable 'answer' in the near header of the class.
Later on when, a random number within an entered range has been generated, that same variable gets a new different value (due to the random generator). But as you can see, the variable 'answer' is indicated in two different colors (blue vs light brown), and as you expect, the routines that I have made are therefore not working. Somehow answer is not equal to answer. What did I do wrongly???? (unfortunately here you don't see the difference in colors).
In eclipse the color of 'answer' at the very top static int answer = 0; is BLUE.
But the one int answer = ThreadLocalRandom.current().nextInt(1, userinput); is GREY
Here's my code:
package Package1;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Scanner;
public class test6KOPIE
{
static int numberofattempts = 0;
static int maxnummerofattemptsallowed = 5;
static int answer = 0;
public static void main(String[] args)
{
if (answer == 0)
{
Scanner maxinput = new Scanner(System.in);
System.out.println("Under which number do you want to guess");
int userinput = maxinput.nextInt();
int answer = ThreadLocalRandom.current().nextInt(1, userinput);
System.out.println(answer);
main(args);
}
else if (numberofattempts < maxnummerofattemptsallowed)
{
Scanner higherlower = new Scanner(System.in);
System.out.println("Higher or Lower");
int digit = higherlower.nextInt();
if (answer == digit)
{
System.out.println("very well");
}
else {
if (answer > digit )
{
++numberofattempts;
System.out.println("Higher, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
System.out.println(numberofattempts);
main(args);
}
else
{
++numberofattempts;
System.out.println("Lower, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
main(args);
}
}
higherlower.close();
}
else {
System.out.println("Maximum number of attempts used, the answer was" +answer);
}
}
This is because you are re-initializing your answer variable by retyping int before it. If you simply want to reassign the value, the line should be:
answer=ThreadLocalRandom.current().nextInt(1, userinput);

if char equals a letter then execute a code

Please help I cannot run this block of code:
import java.util.Scanner;
public class Methods_in_java {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize = true;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}
charAt is zero based.
You should use ab.charAt(0) if you use only a single char.
Another good advice is to start method names with a lower case and use the camelCase format.
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
Is fir supposed to be the first character in the user String? In that case you want to make sure to take zero-based indexing into account:
char fir = Character.toUpperCase(ab.charAt(0));
You have initialized your prize variable as true that will remain always true even its meet if condition or not just change it to false.
and as you were accessing the String's 2nd character using charAt(1), the index starts from 0 and if you try using charAt(0) then you will access 1st character.
Just change your code to:
public class cn {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize=false;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(0));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}
It would be helpful if you elaborated more on what your problem is,
do you have a run time error, a compile time error, or it the output just not what you'd expect.
Your problem may be that arrays start at 0 so the first letter is charAt(0).
Actually I believe another user mentioned that the prize variable was initialized to true. I believe that that is the issue and that answer should be marked correct.

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

if statement not working properly with variables from another method

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() == ....)

Categories