Looping through Arrays in Java - java

I am trying to write a program to simulate an airline reservation system. I an supposed to use an array of type boolean to represent the number of seats. First five seats represent first class and last five represent economy. Initially the program must allow the user to make a choice between first class and economy and then his choice is processed as follows:
A user can only be assigned an empty seat in the class he chooses.
Once a class is full, the user is offered the option to move to the next class
If the user agrees to move to the next class a simple boarding pass is printed.
If the user refuses to move to the next class. The time for the next flight is displayed. i would appreciate help on how to loop through the elements of the array to determine whether its true of false. Also i am trying to display the number of seats available in each class before the user makes a selection this is what i've written so far.. My code is far from complete, i acknowledge that, i am a novice programmer please help. Thank you.
import java.util.Scanner;
public class AirlineReservation
{
private boolean[] seats =; // array to hold seating capacity
private String AirlineName; // name of airline
private int[] counter = new int[5]
// constructor to initialize name and seats
public Airline(String name, boolean[] capacity )
{
AirlineName = name;
seats = capacity;
} // end constructor
// method to set the Airline name
public void setName( String name )
{
AirlineName = name; // store the course name
} // end method setCourseName
// method to retreive the course name
public String getName()
{
return AirlineName;
} // end method getName
// display a welcome message to the Airline user
public void displayMessage()
{
// display welcome message to the user
System.out.printf("Welcome to the Self-Service menu for\n%s!\n\n",
getName() );
} // end method displayMessage
// processUserRequest
public void processUserRequest()
{
// output welcome message
displayMessage();
// call methods statusA and StatusB
System.out.printf("\n%s %d:\n%s %d:\n\n",
"Number of available seats in First class category is:", statusA(),
"Number of available seats in Economy is", statusB() );
// call method choice
choice();
// call method determine availability
availability();
// call method boarding pass
boardingPass();
} // end method processUserRequest
public int statusA()
{
for ( int counter = 0; counter <= (seats.length)/2; counter++ )
} // revisit method
// method to ask users choice
public String choice()
{
System.out.printf(" Enter 0 to select First Class or 1 to select Economy:")
Scanner input = new Scanner( System.in );
boolean choice = input.nextBoolean();
} // end method choice
// method to check availability of user request
public String availability()
{
if ( input == 0)
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
else
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
}
}

#Anthony : As you are novice, hence please look at following comments :
1. Be specific while asking your question. In this case the question was "how to loop through array!". You posted complete problem statement.
2. Please google it or research it properly on internet if similar question has been asked by anybody before. In this case, similar question can be find here :
Iterate through string array in Java
Because of these reasons people are giving your query downvote!
Now just want to provide answer to your question as you look quite new to programming :
boolean flag[] = {true,false,true,false};
for(int i=0;i<flag.length;i++){
System.out.println(flag[i]);
}
I hope it helps!

Related

JAVA seperate class method not incrementing a variable in my main class method

so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");

Java Shooting targets

I have been working on this for almost one week. The question is mainly about shooting the target. So we ask the user to input v0, degree, x0, and y0. We will be setting two targets(500,0)&(1000,0).
I think I did all the methods correctly except for the main methos.
The question I am having now is I have no idea about how to put the "return"s back to the main method.(For example, I got the time and I returned it, but how can I output "The time it took to get to the groud is +time+".
It is my first time working with method questions, I would be happy to see some advice!!
Also I've been told to give the user 4 chances to play this game and give the user to choose whether they are going to start again or exit. I saw many people useing boolean to work this part, but I have no idea about how to use it.
The following is what I got so far:
import java.io.*;
public class AngryBirdGame{
public static void main(String[] args) throws IOException{
int vo,degree = 0,xo = 0,yo = 0;
System.out.println("This game is the Angry Bird Game. You will be trying to hit the target.");
System.out.println("One of the targets of the game is (500,0)");
System.out.println("The other target of the game is (1000,0)");
System.out.println("Please enter the initial velocity");
vo=velocity();
System.out.println("Please enter the angle of elevation(0-90 degrees)");
degree=degree(degree);
System.out.println("Please enter the horizontal starting point(50-500)");
xo=horizontal(xo);
System.out.println("Please enter the vertical starting point");
yo=vertical(yo);
result(0);
}
In order to allow the user to play multiple games, you need a loop in your main() method. Also, as a matter of organization, it would be convenient to define a class that encapsulated all the data the user needs to provide to get a game started. (The class AngryBirdGame probably works just fine for that.) You can then extract all the logic for obtaining the user's input into a separate method that returns an instance of the game data class, or null if the user doesn't want to play any more. Similarly, you should define a method that returns the result of the game so you can report the result to the user each time through the loop.
Finally, my guess is that your input variables should be floating point numbers (or maybe even double) rather than int values. It's hard to do trajectory calculations accurately using integer values only.
Putting all that together, here's an outline of what it might look like:
public class AngryBirdGame {
float vo, degree, xo, yo;
public static void main(String[] args) {
printOneTimeIntro();
Scanner in = new Scanner(System.in);
for (int i = 0, AngryBirdGame game = getGameInfo(in);
i < 4 && game != null;
i++, game = getGameInfo()) {
float time = game.play();
System.out.format("The time it took to get to the ground is %f%n", time);
}
}
/**
* A static method to print a one-time introduction to the program.
*/
private static void printOneTimeIntro() {
System.out.println("This game is the Angry Bird Game. You will be trying to hit the target.");
}
/**
* A static method to check whether the user wants to play and, if so,
* to collect all the game info.
*
* #return a game object, or {#code null} if the user no longer wants to play.
*/
private static AngryBirdGame getGameInfo(Scanner in) {
// first check if the user wants to play
System.out.println("Do you want to play (y/n)? ");
String input = in.next();
if (input.toLowerCase().startsWith("n")) {
return null;
}
// if so, create a game object and get all the input
AngryBirdGame game = new AngryBirdGame();
System.out.println("One of the targets of the game is (500,0)");
System.out.println("The other target of the game is (1000,0)");
System.out.println("Please enter the initial velocity");
game.v0 = in.nextFloat();
// TODO: get rest of input
return game;
}
/**
* An instance method that plays the game once everything is initialized.
*
* #return the time it takes for the trajectory to complete
*/
private float play() {
float time;
// TODO: calculate the game time to reach the ground
return time;
}
}
Note that if you want to return more information than just the trajectory time, you might want to define a second class to contain everything you want returned and use that as the return value from play().

Beginning Java: Utilizing user's input

I am new to learning Java and in my class i have an assignment ive been struggling with:
You need to create three classes: Duck, Dog, and DuckDogApp. DuckDogApp would use Duck and Dog objects. You may use three separate different files or just one file to contain three classes. Your program:
1.Prompt a user to input “duck” or “dog” from keyboard (ask a question)
The output should display “Quack! Quack!” if the user’s input is “duck”, and followed by a new question “dog or duck?” and give a program to end the program
If the user chooses to end the program, then game is over. If the user’s input is “dog”, next prompt should be: “what size is your dog?”
if the user’s input is negative or 0, the program would tell the user to enter a correct number:
once the user typed in a number and hit enter:
-the output should be “Yip! Yip! Yip!” if the number is between 1 and 14;
-the output should be “Ruff! Ruff! Ruff!” if the number is between 15 and 59;
-the output should be “Woof! Woof! Woof!” if the number is more than 60.
End of the program
If the user input is “dog”, output should follow the step 2.
I am having difficulties understanding what to do next or if what i have is even right. I dont know how to go about utilizing the users input from "what size is your dog" to the bark. This is my first Java class so again, im new- any tips would be greatly appreciated- im having difficulties getting the hang of it. So far this is my code:
import java.util.*;
class Duck{
}
class Dog{
private int size;
public int getSize(){
return size;
}
public void setSize(int n){
size=n;
}
public void bark(){
if (size>60){
System.out.println("Woof! Woof!");
}
else if (size>14){
System.out.println("Ruff! Ruff!");
}
else{
System.out.println("Yip! Yip!");
}
}
}
class DogDuckApp{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Dog or Duck?");
String userinput = input.nextLine();
/*If user inputs dog (disregarding case) it will ask what size the dog is*/
if("Dog".equalsIgnoreCase(userinput))
{
System.out.println("what size is your dog?")
}
}
/*If user inputs duck (disregarding case) it will display Quack! Quack!*/
if("Duck".equalsIgnoreCase(userinput))
{
System.out.println("Quack! Quack!");
}
}
}

Making a program repeat within itself, but you can't make a method(?): Java

I have a project for my computer science class and we're making battleship. Part of the program is that we have make sure that the piece the player puts down does not go off of the board.
I've made a method to check to see whether it goes off the board:
private static boolean test(String s, int row, int column,int spaces)
{
if(s.equals("right")&&column+5<=10)
{
return true;
}
if(s.equals("up")&&row-spaces>=0)
{
return true;
}
if(s.equals("left")&&column-spaces>=0)
{
return true;
}
if(s.equals("Down")&&row+spaces<=10)
{
return true;
}
return false;
}
But once I've gotten it to print out an error message, I'm not sure how to make it so that the program can re-recieve the new position for the piece, without putting an if statement in and if statement in an if statement (and on and on), because you need to check the new position to make sure it doesn't go off of the board.
Here is the part where I get the position of the playing piece (although I don't think you need it)
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
And here's one of the if statements that I use to check/place the pieces
if(direction.equals("left")&&test("left",beginrow,begincolumn,5))
{
for(int i = beginrow; i>beginrow-5; i--)
{
battleship[begincolumn-1][i-1] = ('a');
}
}
else if(!test("left",beginrow,begincolumn,5))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
This may be a duplicate, but I didn't know how to reword my search to find what I wanted. (So if anyone could direct me to the right article, that'd be nice as well)
What you should do is split your code appropriately into methods and call that methods repeatedly until your program is satisfied with the outcome.
For example:
create a method startGame() which has the job call methods getting user input until satisfied
make a method to request the user to input all the different ships and other required data
That might look something like
public void startGame() {
// do some setup
while(!requestShipInput()) { // request ship data until the data is valid
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
// do some more ship setup
// get the actual playing started
}
public boolean requestShipInput() {
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
if(direction.equals("left")&&test("left",beginrow,begincolumn,5)) {
for(int i = beginrow; i>beginrow-5; i--) {
battleship[begincolumn-1][i-1] = ('a');
}
return true; // valid ship data
}
return false; // invalid ship data
}
As a first step, separate input validation from taking the action based on that input - you already have the validation logic in a separate function, so this is easy. Then figure out what needs to be done in case of invalid input - in your case, you need to ask for new input until you get a valid position:
do {
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
direction = sonic.next();
} while (!test(direction, beginrow, begincolumn, 5))
After that, you know you've got a valid position.
My next step would probably be to group the information required to describe a ship on the board (i.e. beginrow,begincolumn,direction, probably also size) in a separate Object - possibly named Ship.
I think you could pretty naturally use recursion here:
public void getInput() {
// scanner code to get input
if (!test("left",beginrow,begincolumn,5)) { // test failed
getInput()
return
}
// test succeeded, continue
}
You already have something to the limits of you board? If you execute the check first, you don't need to execute a cascade of if-else
if(!test(direction,beginrow,begincolumn,size))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
} else {
// check for collision with already placed ships
}
Keep in mind that there is a chance to combine up/down and left/right. The calculation rules are nearly the same and you only have to decide if you have to look to the one or the other direction.

Java Help: Using Classes

Now I have read and on this but i am just stuck. Any help appreciated. I am looking for hints. The code compiles and runs fine but I don't think the variables are being stored in the employee class and I am not sure I am understanding my use of the constructor right.
Requirements:
I have completed:
Values are checked to ensure they are
positive numbers.
Entering stop as the
employee name end program.
Having trouble on
Uses a class to store
name
hourly rate
hours worked
Use a constructor to initialize the employee information
and a method within that class to
calculate the weekly pay.
Here are a couple hints:
Use a constructor to initialize the
employee information
Looking at the provided code, there is a single constructor which takes no arguments and will initialize the fields of the object to zero.
Perhaps the "constructor to initialize the employee information" means that the constructor should be able to accept values which the Employee object should initlialize its fields to.
The Java Tutorials has a page on Providing Constructors for Your Classes with examples which should help in creating such constructor.
... and a method within that class to
calculate the weekly pay
This seems to say that there should be a method that is only visible to itself and not available from others in order to calculate the value for the weeklyPay field.
Again, from The Java Tutorials, Controlling Access to Members of a Class discusses show to change the visibility of methods.
Reading the contents of the assignment, it seems like taking a look at the Lesson: Classes and Objects of The Java Tutorials may be of use, as it provides some good examples and explanations on the concepts of object-oriented programming.
In addition to the fact that you haven't used the constructor to set your variables, as mentioned by others. The setter methods are performing no-ops. Which is why you aren't getting the results you expect. You are setting the local var to itself and not to the member var.
You need to either change your local var names, change the member var names, or change the setters to use the 'this' keyword
public void sethoursWorked(float hoursWorked)
{
this.hoursWorked = hoursWorked;
}
You'll notice that you are asked to make a class that stores the name, the hourly rate, and the hours worked, while you are asked to make a method that calculates the weekly pay. In other words, you should not have a weeklyPay instance variable. Whenever the user asks for the weekly pay (by means of your getWeeklyPay() method), you calculate and return it directly, without storing it in an instance variable.
Then, in order to actually use that result, you'll need to change this:
Employee.getweeklyPay();// Calculate weeklyPay ( hoursWorked * hourlyRate )
weeklyPay = ( hoursWorked * hourlyRate );
into something like this:
weeklyPay = employee.getWeeklyPay();
If you don't actually assign the result of your method to some variable, you can't use the result.
The final answer from the OP:
/** Payroll3.java | Due 8/09/09
** IT 2015 Java Programming | lazfsh | Axia College - University of Phoenix */
import java.util.Scanner;// Import and use scanner
public class Payroll3 {// main method begins
public static void main( String args[] ) {
// Initialize
boolean stop = false;// Variable for exit procedure
String endProgram = "";// Variable to explain exit procedures blank 1st time
int version = 3;// Version number
// Welcome message
System.out.printf(
"\nWelcome to the Payroll Program v.%d\n", version );//Welcome message
while ( stop == false) {// Run program until stop equals true
Scanner input = new Scanner( System.in );// new Scanner for CL input
Employee Employee = new Employee(); // new Employee constructor
// Prompt for and input name
System.out.printf( "\nEnter name of the employee%s:", endProgram );
Employee.setempName(input.nextLine());// Accept input & Store
if ( Employee.getempName().equals( "stop" )) {// If = end program w/message
System.out.printf( "\n%s\n%s\n\n", "....", "Thanks for using Payroll Program");
stop = true;}
else{// Continue retrieve hourlyRate, hoursWorked & Calculate
do {// Prompt for and input hourlyRate
System.out.printf( "\n%s", "Enter hourly rate: $" );
Employee.sethourlyRate(input.nextFloat());// Accept input & Store
if ( Employee.gethourlyRate() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethourlyRate() < 1 );// End loop if positive number recieved
do {// Prompt for and input hoursWorked
System.out.printf( "\n%s", "Enter number of hours worked:" );
Employee.sethoursWorked(input.nextFloat());// Accept input & Store
if ( Employee.gethoursWorked() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethoursWorked() < 1 );// End loop if positive number recieved
// Display formatted results
System.out.printf( "\n%s's weekly pay is $%,.2f\nHourly rate ($%,.2f) multiplied by hours worked (%.0f)\n\n...Ready for next employee.\n\n",
Employee.getempName(), Employee.getweeklyPay(), Employee.gethourlyRate(), Employee.gethoursWorked() );
// Debug Line Employee.showVariables();
}// end retrieve hourlyRate, hoursWorked & Calculate
endProgram = ( ", \n(Or type \"stop\" to end the program)" );//explain exit procedure on second empName prompt
}// ends program when stop equals true
}// end method main
}//end class Payroll3
Employee class
/** Employee Class | Initializes and storeds data for employee
Also provides method to calculate weekly pay.
*/
// Import statements
import java.util.Scanner;// Import and use scanner
public class Employee {//Begin Employee class
Scanner input = new Scanner( System.in );// new Scanner for CL input
// Declare instance variables
String empName; // Declare name as string
float hourlyRate; // Declare hourlyRate as float
float hoursWorked; // Declare hoursWorked as float
// constructor initializes employee information
public Employee() { // Initialize (clear) instance variables here
empName = "";
hourlyRate = 0;
hoursWorked = 0;
} // end constructor
// Begin methods
public void setempName(String empName) {// public method to set the employee name
this.empName = empName;}// end method setempName
public String getempName() {// public method to get the employee name
return empName;}// end method getempName
public void sethourlyRate(float hourlyRate) {// public method to set the hourly Rate
this.hourlyRate = hourlyRate;}// end method set hourly Rate
public float gethourlyRate() {// public method to retrieve the hourly Rate
return hourlyRate;} // end method get hourly Rate
public void sethoursWorked(float hoursWorked) {// public method to set the hours Worked
this.hoursWorked = hoursWorked;} // end method set hours Worked
public float gethoursWorked() {// public method to retrieve the hours Worked
return hoursWorked;} // end method get hours Worked
public float getweeklyPay() {// public method to retrieve weekly Pay
return ( hoursWorked * hourlyRate );}// end method get weeklyPay
/* Test line
public void showVariables(){
System.out.printf( "empName=%s, hourlyRate=%s, hoursWorked=%s", this.empName, this.hourlyRate, this.hoursWorked );} */
} // end class Employee

Categories