Comparing a scanner input to elements in an array - java

I am new to java so forgive me if I am making a very simple mistake. I am attempting to make shop within a text based adventure game. I have created an array shopItems which stores a list of items as strings that the shop can sell. Here is a part of the method I use for the user to make purchases within the game.
String request = s.nextLine().toLowerCase();
for (int i = 0 ; i < shopItems.length ; i++)
{
if(request.equalsIgnoreCase(shopItems[i]))
{
System.out.println("We have this item in stock! That will be " + itemPrice[i] + " gold, "
+ "would you like to purchase this item?");
String command2 = s.nextLine().toLowerCase();
if(command2.equals("yes") || command2.equals("y"))
{
if (savings >= itemPrice[i])
{
System.out.println("Congratulations! You have purchased " + shopItems[i] + ". Thank you "
+ "for your business.");
savings = savings - itemPrice[i];
inv.add(shopItems[i]);
magicShopPurchase();
}
else if (savings < itemPrice[i])
{
System.out.println("I'm sorry, you don't have enough gold to purchase this item! Try "
+ "again when you have enough!");
}
}
}
else if(request.equals("leave"))
{
System.out.println("Thank you! Please come again soon!");
inMagicShop();
}
else
{
System.out.println("I'm sorry, we don't have any of those in stock at the moment. Would you "
+ "like to purchase a different item?");
String command2 = s.nextLine().toLowerCase();
if(command2.equals("yes") || command2.equals("y"))
{
magicShopPurchase();
}
else if(command2.equals("no") || command2.equals("n"))
{
System.out.println("Thank you! Please come again soon!");
inMagicShop();
}
else
{
System.out.println("Haha, you kiss your mother with that mouth? Come back some other time!");
inMagicShop();
}
}
}
I am trying to compare the scanner input with shopItems to check if the item that the user wants to purchase is available in the shop, however it does not recognize any of the elements in shopItems. Am I doing something wrong with this method/is there a mistake somewhere? This is my first post here so please forgive me if I have left out anything important.
EDIT
First is where I call the method to store elements into shopItems.
try {
itemList = new String(Files.readAllBytes(Paths.get("C:\\Users\\gravy_000\\Desktop\\Software Development 1\\GameProject\\src\\hallSim\\magicitems.txt")));
read(itemList);
} catch (IOException e) {
e.printStackTrace();
}
Second is the method I used to read the text file and store it into shopItems.
public static void read(String shopList) {
shopItems = shopList.split("\\r?\\n");
}
Here is a link to the text file in Dropbox
https://www.dropbox.com/s/rbfsr1fj2yzus1q/magicitems.txt?dl=0

The problem is that you are telling the user that the item is not found, the first time request.equalsIgnoreCase(shopItems[i]) returns false, NOT when request is not present.
So you should replace the code by something like this or equivalent:
String request = s.nextLine().toLowerCase();
if(request.equals("leave")) {
//leave
} else {
boolean isItemInStock = false;
for (int i = 0 ; i < shopItems.length ; i++) {
if(request.equalsIgnoreCase(shopItems[i])) {
isItemInStock = true;
break;
}
}
if(isItemInStock) {
System.out.println("We have this item in stock! That will be " + itemPrice[i] + " gold, "
+ "would you like to purchase this item?");
//...
} else {
System.out.println("I'm sorry, we don't have any of those in stock at the moment. Would you "
+ "like to purchase a different item?");
//...
}
}
Note how the if/else statement that handles what to with request is outside the main loop.

Related

If/else statements written as loops

I heard that one can turn the if/else statements into loops, they are somewhat equivalent. Could someone give me an example, because I am having a hard time understanding the conversion process.
Ok from the comments I guess I didn't ask the question correctly. I am basically working on an assignment and have to use someone's code which was written in all if/else statements and convert it into a code that includes loops.
I am not asking for the answer to this problem but I am asking for an example on how one would do this. I've pretty much though of a way of doing it, with the code below. It's basically a Haunted House maze type of "game" that ends whenever you touch and explore an object after going through rooms, but there is no backtracking. With loops I have to allow backtracking, and allow the user to explore as many items as possible, and only end the game when the user decides to end it.
EDIT:
Okay, I've started to convert the Living Room section path of the code above into a while loop. Please tell me if it looks good, if I could improve it somehow, or if I made any mistakes, it seems to run fine. The only problem I have is that when I click decide to go use the chest, it asks twice and then ends, it should only ask once, the same with the Candelabra. Maybe I am missing something about the "break" statement? But I don't know because when I am in the pantry, and then go back, and I have the if else contain just break; it does what it is supposed to do... but not with the chest and the candelabra.
But here is my code so far:
public class LoopyHauntedHouse {
private String name; //Player name.
private String location0; //First location selected from door.
private String toFrontDoor = "";
private String atFrontDoor;
//Method asking for user's name, and welcoming the user as well as asking where they'd like to go for the first time.
public void intro()throws MalformedURLException
{
//URL to image initialized from the original code as needed.
URL frontDoor = new URL("http://i.imgur.com/2m3giQk.png");
//Scanner for user input.
Scanner scnr = new Scanner(System.in);
//Asking for user's name and welcoming the user.
name = JOptionPane.showInputDialog(null, "What is your name?");
JOptionPane.showMessageDialog(null, "Welcome " + name + " to the Haunted House!");
//Shows starting location.
JOptionPane.showMessageDialog(null, name + " you're at the front door of the haunted house.", "Title",
JOptionPane.PLAIN_MESSAGE, new ImageIcon(frontDoor));
//Asks for first choice of room to start at.
location0 = JOptionPane.showInputDialog(null, name + " where to next? 'Living Room', 'Dining Room' or 'Stairs'?");
}
//Method for the rest of the program allowing users to walk through the house, backtrack, and interact with objects.
public void startWalking()throws MalformedURLException
{
//URLs to images are initialized from the original code as needed.
URL stairs = new URL("http://i.imgur.com/WuddJUc.png");
URL bedroom1 = new URL("http://i.imgur.com/HZ6OSyZ.png");
URL bedroom2 = new URL("http://i.imgur.com/JZORNpd.png");
URL bathroom = new URL("http://i.imgur.com/onSEc1J.png");
URL masterBedroom = new URL("http://i.imgur.com/bf4L0sH.png");
URL masterBathroom = new URL("http://i.imgur.com/yp87dTX.png");
URL livingRoom = new URL("http://i.imgur.com/7XQD5Pt.png");
URL bathRoom = new URL("http://i.imgur.com/G0CxjSy.png");
URL diningRoom = new URL("http://i.imgur.com/gyU9mep.png");
URL kitchen = new URL("http://i.imgur.com/tTMRCID.png");
URL pantry = new URL("http://i.imgur.com/zBxPJCs.png");
while(location0.equalsIgnoreCase("Living Room")||(toFrontDoor.equalsIgnoreCase("Living Room")))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Living Room");
String move1 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Chest' walk to the 'Bathroom' or 'Go back' and go to another room?");
if(move1.equalsIgnoreCase("Chest"))
{
JOptionPane.showMessageDialog(null, name + " a ghost escapes and scares you to death!");
JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.",
JOptionPane.WARNING_MESSAGE, new ImageIcon(livingRoom));
break;
}
else if(move1.equalsIgnoreCase("Bathroom"))
{
while(move1.equalsIgnoreCase("Bathroom"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the bathroom.");
String move2 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Mirror', 'Shower', or 'Go back'?");
if(move2.equalsIgnoreCase("Shower"))
{
JOptionPane.showMessageDialog(null, name + " the room suddenly steams up and you feel fingers touching the back of your neck...");
}
else if(move2.equalsIgnoreCase("Mirror"))
{
JOptionPane.showMessageDialog(null, name + "you see a bloody face looking back at you!");
}
else if(move2.equalsIgnoreCase("Go back"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Living Room");
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
}
else if(move1.equalsIgnoreCase("Go back"))
{
toFrontDoor = move1;
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
while(location0.equalsIgnoreCase("Dining Room"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Dining Room");
String move1 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Candelabra' or walk to the 'Kitchen'");
if(move1.equalsIgnoreCase("Candelabra"))
{
JOptionPane.showMessageDialog(null, "The candelabra light up by themselves and " + name + " sees a death shadow!");
JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.",
JOptionPane.WARNING_MESSAGE, new ImageIcon(diningRoom));
break;
}
else if(move1.equalsIgnoreCase("Kitchen"))
{
while(move1.equalsIgnoreCase("Kitchen"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the 'Kitchen'.");
String move2 = JOptionPane.showInputDialog(null, name + " would you like to explore either the 'Refrigerator' or 'Cabinet' walk to the 'Pantry', or 'Go back'");
if(move2.equalsIgnoreCase("Refrigerator"))
{
JOptionPane.showMessageDialog(null, name + " opens the refrigerator and finds some delicious soul food.");
}
else if(move2.equalsIgnoreCase("Cabiner"))
{
JOptionPane.showMessageDialog(null, "The dished and glasses start flying at you as soon as you open the door. " + name + " gets hit in the head and feels themselves moving towards a light.");
JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.",
JOptionPane.WARNING_MESSAGE, new ImageIcon(kitchen));
break;
}
else if(move2.equalsIgnoreCase("Pantry"))
{
while(move2.equalsIgnoreCase("Pantry"))
{
JOptionPane.showMessageDialog(null, name + " you are now in the Pantry.");
String move3 = JOptionPane.showInputDialog(null, name + " would like to explore the 'Dusty Recipe Box', the 'Broom', or 'Go back'?");
if(move3.equalsIgnoreCase("Dusty Recipe Box"))
{
JOptionPane.showMessageDialog(null, name + "opens it up and a recipe for chocolate devils food cake appears out of no where.");
}
else if(move3.equalsIgnoreCase("Broom"))
{
JOptionPane.showMessageDialog(null, "As soon as " + name + " touches the broom, it flies up in the air!");
}
else if(move3.equalsIgnoreCase("Go back"))
{
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
}
else if(move2.equalsIgnoreCase("Go back"))
{
toFrontDoor = move2;
break;
}
else
{
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
}
}
}
}
}
public void toFrontDoor() throws MalformedURLException
{
if(toFrontDoor.equalsIgnoreCase("Go back"))
{
atFrontDoor = JOptionPane.showInputDialog(null, name + " where to next? 'Living Room', 'Dining Room', 'Stairs', or 'Leave the house'?");
if(atFrontDoor.equalsIgnoreCase("Leave the house"))
{
JOptionPane.showMessageDialog(null, "Game Over! Thanks for playing.");
}
}
else
{
startWalking();
}
}
}
Test CLass:
public class LoopyTest {
public static void main(String[] args) throws MalformedURLException {
LoopyHauntedHouse player = new LoopyHauntedHouse();
player.intro();
player.startWalking();
player.toFrontDoor();
}
}
Yes, in assembly language, loops are implemented with condition statement and a goto statement:
L1: if ( <cond> )
{
<loop-body>
goto L1 ;
}
You can use this approach in C, but not in Java because goto is not permitted.
When program gets to L1, it checks the condition. If the condition is met, program will proceed with loop-body, after that it will jump (goto) to L1 which labels a line number in your program. There, a loop. It will break if the condition is not met and program will continue at next line after curly brace { .
You can make a loop that does the functional equivalent of an if statement if you're careful about how you design it.
If:
if(myVal == 1) {
//do something
}
Functionally equivalent for:
for(int i = myVal; i == 1; ++i) {
//Do something
}
Functionally equivalent while:
int i = myVal;
while(i == 1) {
//Do something
++i;
}
Notice, that in the loops I don't directly compare myVal against the loop terminator. This is because you have to change the comparison value in order to get out of the loop, and you may not want to change your actually variable.
However, if your entire desired code was running inside a while(isPlaying) {}, you don't need a bunch of other loops. You just add else if(move#.equalsIgnoreCase("quit") {isPlaying = false; } for all the places you check each move#.
I would also add, that your current code could benefit from using classes. There's really no reason to have a new move# variable for each command the user enters.
Since the different rooms are kind of the "state". you could probably solve it when using the state pattern. Each state is represented by one obect. Using those objects, each can decide what to do next based on it's state. For example:
class Room {
private String roomName;
private URL icon;
private List<String> nextRooms;
public Room(String _roomName, URL _icon, String... _nextRooms) {
roomName = _roomName;
icon = _icon;
nextRooms = new ArrayList<>();
for (String string : _nextRooms) {
nextRooms.add(string.toLowerCase());
}
}
public void showInfo(String player) {
JOptionPane.showMessageDialog(null, player + " you're in " + roomName, "Title",
JOptionPane.PLAIN_MESSAGE, new ImageIcon(icon));
}
public String nextRoomName(String player) {
StringBuilder sb = new StringBuilder();
for (String string : nextRooms) {
sb.append(string).append(", ");
}
String roomOptions = sb.toString();
while(true) {
String input = JOptionPane.showInputDialog(null, player + " where to next? Your options are: " + roomOptions);
if(nextRooms.contains(input)) {
return input;
}
}
}
}
public void start() throws MalformedURLException {
Map<String, Room> rooms = new HashMap<>();
rooms.put("room a", new Room("Room A", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room B", "Room C"));
rooms.put("room b", new Room("Room B", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room A"));
rooms.put("room c", new Room("Room C", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room A", "Win"));
String player = JOptionPane.showInputDialog(null, "What is your name?");
JOptionPane.showMessageDialog(null, "Welcome " + player + " to the Haunted House!");
Room room = rooms.get("room a");
while (true) {
room.showInfo(player);
String nextRoom = room.nextRoomName(player).toLowerCase();
if ("win".equalsIgnoreCase(nextRoom)) {
return;
}
if (rooms.containsKey(nextRoom)) {
room = rooms.get(nextRoom);
}
}
}
That's kind of complicated, especially if you're new to Java or Object Oriented , so alternatively make each room a method. And depending on what the user decides, call the appropriate method and so on.
void start() {
roomA();
}
void roomA() {
String input = JOptionPane....
if (input.equals("Room B")) {
roomB();
}
}
void roomB() {
String input = JOptionPane....
if (input.equals("Room A")) {
roomA();
} else if (input.equals("win")) {
win();
}
}
void win() {
JOptionPane.showMessageDialog...
}

Need to start again at a certain point in java

I'm really new to java, and just programming in general. I am trying to make a simple "story game".
I want the program to start again where I commented "starting again point if walk.equals("b") (second time)"
Here is my code:
P.S. sorry if it is poorly written
import java.util.*;
public class leikur1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("|---------Welcome to the adventure------------|");
System.out.println("Please enter Name"); // inputs name
String nafn = scan.nextLine();
nafn = nafn.toLowerCase();
System.out.println("Gender, male or female");
String kyn = scan.nextLine();
kyn = kyn.toLowerCase();
while((!kyn.equals("male")) && (!kyn.equals("female")) ) //bara haegt ad velja male eda female
{
System.out.println("That is not valid input" );
kyn = scan.nextLine();
kyn = kyn.toLowerCase();
}
System.out.println("Are you ready for the adventure");
String leikur = scan.nextLine();
leikur = leikur.toLowerCase();
while((!leikur.equals("yes")) && (!leikur.equals("no")) ) //impossible to input something else than male or female
{
System.out.println("That is not valid input" );
leikur = scan.nextLine();
leikur = leikur.toLowerCase();
}
if(leikur.equals("no"))
{
System.out.println("Thank you anyway"); //if input = no program ends
}
// if input = yes the game begins
else
{
System.out.println("Write Start to begin or Quit to exit");
String start = scan.nextLine();
start = start.toLowerCase();
String gender;
if(kyn.equals("male"))
{
gender = "he";
}
else
{
gender = "she";
}
while((!start.equals("start")) && (!start.equals("quit")) )
{
System.out.println("That is not valid input" );
start = scan.nextLine();
start = start.toLowerCase();
}
if(start.equals("start"))
{
System.out.println("Walking instructions: left - l right - r forward - f back - b down - d up - u\n");
System.out.println(nafn + " is in a abandoned house late at night, stuck in the basement with no light.\n");
System.out.println("In wich way should " + gender + " go to find his way to the stairs?" ); **// starting again point if walk.equals("b") (second time)**
String walk = scan.nextLine();
walk = walk.toLowerCase();
//////////
while((!walk.equals("f")) && (!walk.equals("b")) ) // not possible bcus of walls or no stairs
{
System.out.println("That is not possible" );
walk = scan.nextLine();
}
if(walk.equals("f"))
{
System.out.println("Great choice, " + gender + " found the stairs right away. Should"+gender+" go upstairs or go back?" );
}
else if (walk.equals("b"))
{
System.out.println("Oh boy! " + nafn +" got stuck in a beartrap and died... GAME OVER" );
}
/////////
walk = scan.nextLine();
while(!walk.equals("u") && !walk.equals("b") )
{
System.out.println("That is not possible" );
walk = scan.nextLine();
}
if(walk.equals("u"))
{
System.out.println("Excelent!" + nafn + " is now upstairs" );
}
**else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
}**
//////////////
// code 4 the game should be here above
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
}
}
}
}
If you just want to repeat your content, a while loop is sufficient
boolean continue = true;
while(continue)
{
else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
continue = true;
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
continue = false;
}
}
the reason I'm using the variable continue is to better illustrate the while loop. you can also use while(true), which will normally loop forever. to skip to the beginning of the next iteration you use continue; and to break out, you can use break
while(true)
{
else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
continue;
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
break;
}
}
If you really wanted to take your coding to the next level, you could take a more data-driven approach, and have a data model to define your game. The following is a sample data model in xml
<Places>
<Place name="YourRoom" text="You are in your room. Where would you like to go?">
<Option text="Enter the hallway." result="Hallway"></Option>
</Place>
<Place name="Hallway" text="You are in the hallway. Where would you like to go?">
<Option text="Go to your room" result="YourRoom"></Option>
</Place>
</Places>
And then you'd write your program something like this
pseudocode:
xmlElement currentRoom = // get starting element
while(true)
{
print(currentRoom.Attributes[text])
for(int i=0; i<currentRoom.Elements.length; i++)
{
print(currentRoom.Elements[i] + "type " + i+1;
}
int choice = getInt();
int result = currentRoom.Elements[choice].result;
currentRoom GetElementWithName(result);
}
You should rather learn Java, OOP and other base constructs. If you really insist, you can use labels (to be honest since the advent of structured programming, in the sixties people try not to use GOTO anymore... but if you want to fail a job interview go ahead ;-) )
// ...
// label is your label, you can use any text
label:{
// ...
// here is your GOTO
break label;
}
Side note : it works like a charm, but please don't do it (or at least don't say I'm the one who told you about labels) !

Prompting to print all of that type, and calculate the total of that type

I have a file that is needed to be read:
public static int start_program1(int rcount,int[]reservation_code,int[]fl_number,String[]last_name,String[]first_name,String[]seat_type,double[]seat_cost)
{
String newLine;
try
{
//define a file valuable for Buffered read
BufferedReader Reservation_file = new BufferedReader(new FileReader("reservationx.dat"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Reservation_file.readLine()) != null)
{
//there is a "#" between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine,"#");
rcount=rcount+1;
reservation_code[rcount] = Integer.parseInt(delimiter.nextToken());
fl_number[rcount] = Integer.parseInt(delimiter.nextToken());
last_name[rcount] =delimiter.nextToken();
first_name[rcount] =delimiter.nextToken();
seat_type[rcount] =delimiter.nextToken();
seat_cost[rcount] = Double.parseDouble(delimiter.nextToken());
}//while loop
Reservation_file.close();
}//end try
catch (IOException error)
{
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//error on read
return rcount;
}//end start_system1
The file being read (reservations.dat) is simply below: (Wasn't sure of an easier way to post this)
(reservation code#flight number#last name#first name#seat type#seat cost)
1189#1234#Smith#James#coach#299.99#
1190#9876#Jones#Marie#coach#150.00#
1191#2000#Atkins#John#first#789.00#
1192#1000#Gallo#James#first#465.00#
1193#4567#Marion#Kevin#business#300.00#
1194#4444#Johnson#Greg#business#765.99#
1195#8888#Brown#Andrew#first#567.39#
1196#4567#Green#Eric#coach#234.00#
1197#9876#Thomas#Chris#business#1900.99#
1198#7777#Hilling#Cara#first#876.76#
1199#2222#Cole#James#coach#256.99#
1200#9281#Bartko#Grant#business#896.00#
1201#2000#Best#Curtis#first# 543.99#
1202#1000#Campbell#Nicholas#coach#287.00#
1203#4444#Dietz#Merrialyce#coach# 219.00#
1204#9281#Duran#Alexander#business#690.00#
1205#2892#Gurung#Suraj#first# 789.99#
1206#7777#Kumpfmiller#Ryan#first#278.99#
1207#4444#Mccomb#David#coach#451.99#
1208#8888#Mclain#Jaime#coach#199.00#
1209#9876#Mullen#Matthew#coach#189.00#
1210#1234#Nguyen#Tommy#coach#299.00#
1211#1234#Ossler#Aimee#coach#300.00#
1212#7777#Polenavitch#Michael#coach#198.99#
1213#2222#Raymond#Chase#first#908.99#
1214#2222#Rosales#David#coach#216.99#
1215#2892#Schwartz#Dustin#business#987.00#
1216#4444#Short#Samuel#coach#245.99#
1217#8888#Soltis#Josh#coach#178.00#
1218#1234#Webster#Ronald#business#892.00#
1219#1234#Wielock#William#first#589.00#
1220#2892#Bonelli#Andrew#coach#178.00#
1221#4444#Bright#Adam#coach#235.00#
1222#9876#Clymer#Jesse#coach#568.00#
1223#4444#Costello#Michael#coach#200.00#
1234#7777#Currin#Sean#business#908.00#
1225#1000#Farrar#Gary#first#588.00#
1226#1000#Finn#Lynn#business#799.00#
1227#4567#Freise#Brian#coach#254.00#
1228#4567#Huang#Pao-Jen#coach# 199.00#
1229#4567#Kamani#Nelson#coach#150.00#
1230#2000#Loughner#Ryan#coach#175.00#
1231#2000#Menzies#Adam#coach#199.00#
1232#1234#Neupane#Kiran#coach# 135.00#
1233#1234#Nickel#Brandon#first#999.00#
1234#7777#Ropchack#Joseph#first#899.00#
1235#7777#Whitten#Walter#coach#786.99#
1236#4444#Woods#Mary#coach#299.00#
1237#4444#Xing#Zhenli#coach#126.00#
Here is the method, doing the calculation in question:
public static void seat_value(int rcount,int[]reservation_code,int[]fl_number,String[]last_name,String[]first_name,String[]seat_type,double[]seat_cost)
{
int i;
double total=0;
String search_seat = "";
String output = "Enter the Seat Type you are searching for";
search_seat = JOptionPane.showInputDialog(null,
output, " ",
JOptionPane.QUESTION_MESSAGE);
for (i = 0; i <=rcount; ++i) {
//CHECK IF coach, first, or business
if(seat_type[i].equals("coach"))
{
total=total+seat_cost[i];
}
if (seat_type.equals("first"))
{
total=total+seat_cost[i];
}
if(seat_type.equals("business"))
{
total=total+seat_cost[i];
}
}
System.out.println("The total for " +search_seat+ " = " +total);
}
My issue in detail is this: Whenever I have it prompt for a type ("coach", "first", "business")
I cannot figure out how to get it to print ALL reservations of THAT type & TOTAL COST of THAT type?
CURRENTLY GETTING: 2051.97 8900.94 8094.45
ACTUAL TOTALS: 7230.93 8295.11 8138.98
COACH FIRST BUSINESS
PS, you will obviously call these methods
Hope this is explains it well.
Well in this loop:
for (i = 0; i <=rcount; ++i) {
//CHECK IF coach, first, or business
if(seat_type[i].equals("coach"))
{
total=total+seat_cost[i];
}
if (seat_type[i].equals("first"))
{
total=total+seat_cost[i];
}
if(seat_type[i].equals("business"))
{
total=total+seat_cost[i];
}
}
you add the cost to the same total every single time regardless of the seat type. So you will end up with the total of all the seats each time.
Basically heres what you are doing in english:
I am going to go through each customer. For each customer, I will do the following:
If their seat type is coach, add it to the total.
If their seat type is first, add it to the total.
If their seat type is business, add it to the total.
Basically, you are adding every customers ticket price to the total because every customer will satisfy one of the three conditions you are testing.
You should replace the three if statements with the following:
if(seat_type[i].equals(search_seat)) {
total += seat_cost[i];
System.out.println( reservation_code[i] + "," + fl_number[i] + "," + last_name[i] + "," + first_name[i] + "," + seat_type[i] + "," + seat_cost[i]);
}

Counting the occurrences of a String in an ArrayList

I'm using an ArrayList to save the name, day and time of a show. My program requires me to output the number of shows that play on each day of the week. I've inputted 4 different shows, two of which are on the same day. So far, the only thing the output's given me is "On Thursday there are/is 2 show(s)." The other two didn't show. How can I make is so that it displays the number of shows for each day I've inputted? Here's my code for that:
String showDay = ((showInfo)show.get(0)).day.toString();
int totalShows = 0;
//print occurences for how many shows play each day
for (int i = 0; i < show.size(); i++) {
if (showDay.equals(((showInfo)show.get(i)).day.toString())) {
totalShows++;
}
}
System.out.println("On " + showDay + " there are/is " + totalShows + " show(s).");
}
Here's my code for the shows I input:
//input information
do{
showInfo temp = new showInfo();
System.out.print("Enter the name of show: ");
String showName = br.readLine();
temp.name = showName;
System.out.print("Enter which day of the week a new episode premieres: ");
String showDay = br.readLine();
temp.day = showDay;
System.out.print("Enter time in 24-hour format (e.g. 2100, 1900): ");
int showTime = Integer.valueOf(br.readLine()).intValue();
temp.time = showTime;
show.add(temp);
System.out.print("Would you like to add another show? (y/n) ");
}
while((br.readLine().compareTo("n")) != 0);
Keep in mind that I'm using Java 1.4. No other choice. By teacher's demand.
This is probably obvious, but I'm being oblivious right now. Any help would be great! Thanks in advance!
EDIT:
String showDay = ((showInfo)show.get(0)).day.toString();
if("sunday".equalsIgnoreCase(showDay)){
showdayCount[0]++;
System.out.println("There are/is " + showdayCount[0]++ + " show on Sunday.");
}else if("monday".equalsIgnoreCase(showDay)){
showdayCount[1]++;
System.out.println("There are/is " + showdayCount[1]++ + " show on Monday.");
}else if("tuesday".equalsIgnoreCase(showDay)){
showdayCount[2]++;
System.out.println("There are/is " + showdayCount[2]++ + " show on Tuesday.");
}else if("wednesday".equalsIgnoreCase(showDay)){
showdayCount[3]++;
System.out.println("There are/is " + showdayCount[3]++ + " show on Wednesday.");
}else if("thursday".equalsIgnoreCase(showDay)){
showdayCount[4]++;
System.out.println("There are/is " + showdayCount[4]++ + " show on Thursday.");
}else if("friday".equalsIgnoreCase(showDay)){
showdayCount[5]++;
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
}else if("saturday".equalsIgnoreCase(showDay)){
showdayCount[6]++;
System.out.println("There are/is " + showdayCount[6]++ + " show on Saturday.");
}
This is also only giving me one line. What am I doing wrong?! :(
EDIT:
What I want is to input name/day/time of a TV show, then later be able to display the amount of shows that are on that specific day!
For example, Big Bang Theory and Community are both on Thursday. So the code would output something like
There are 2 shows on Thursday.
Nothing's worked, so far.
You only get one day from this line:
String showDay = ((showInfo)show.get(0)).day.toString();
Here's my hack solution (may have some errors, like a misnamed variable but you should be able to fix it):
//Create a map that maps days to the shows that are on that day
LinkedHashMap showDays=new LinkedHashMap(); //String to Set map
String[] days={"Sunday","Monday", ....};//put the rest of the days in here
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
showDays.put(day,new HashSet());
}
//iterate through the shows and put them in their respective days in the map
for (int i = 0; i < show.size(); i++) {
String dayForShow=((showInfo)show.get(i)).day.toString();
showDays.get(dayForShow).put(show.get(i));
}
//now print out how many shows are on each day
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
int showsToday=showDays.get(day).size();
///do your print out now
}
You can make 'LinkedHashMap showDays' a class variable and add to it each time you add to show (and remove from it each time you remove from show).
PS. Tell your teacher it is no longer 2002, technology moves on and they make my job harder.
Create a Show class
public class Show {
String showName;
String showDay;
int showTime;
static int[] showdayCount = new int[7];
public Show(String showName, String, showDay, iny showTime){
this.showName = showName;
this.showDay = showDay;
this.showTime = showTime;
// increment showDayCOunt[] according to showDay from
switch(showDay){
case "Sunday": showDayCount[0]++; break;
case "Monday": showDayCount[1]++; break;
case "Tuesday": showDayCount[2]++; break;
case "Wednesday": showDayCount[3]++; break;
case "Thursday": showDayCount[4]++; break;
case "Friday": showDayCount[5]++; break;
case "Saturday": showDayCount[6]++; break;
}
}
}
Here's your main method from YourClass
public static void main(String[] args){
// Create Array of Shows
Show[] shosList = new Show[4]; // or how many ever shows you have
// Get your inputs for showName, showDay, showTime
Sting showName =
String showDay =
int showTime =
// Create show Object
Show show = new Show(showName, showDate, showTime);
// add show to ArrayList
showList[someIndex] = show;
// Do all other stuff then print
// when you print, you can get the showDayCount directly from the Show class
}
Now I don't want to do everything for you. I just want to get you headed in the right direction. Note that if you want the above to happen more than once, consider putting inside of a loop.
Edit: With getShowdayCount
Add this to my above Show class
public int getShowdayCount(String showday){
switch(showDay){
case "Sunday": return showDayCount[0]; break;
case "Monday": return showDayCount[1]; break;
case "Tuesday": return showDayCount[2]++; break;
case "Wednesday": return showDayCount[3]++; break;
case "Thursday": return showDayCount[4]++; break;
case "Friday": return showDayCount[5]++; break;
case "Saturday": return showDayCount[6]++; break;
}
}
Edit: With example if/else if from switch statement
// for main method inputs
if ("sunday"equalsIgnoreCase(showDay){
showdayCount[0]++
} else ("monday".equalsIgnoreCase(showDay){
showdayCount[1]++
} // finish if/else if statement
// for getShowdayCount method
if ("sunday"equalsIgnoreCase(showDay){
return showdayCount[0];
} else ("monday".equalsIgnoreCase(showDay){
return showdayCount[1];
} // finish if/else if statement
You can call it from your main class like this
show.getShowdayCount(show.showday);
Edit: Actually, Just put the above edit in you class with the main method
YourClassWithMainMethod{
static int[] showdayCount = new int[7];
public static void mina(String[] args){
// call getShowdayCount here
getShowdayCount(String showday);
}
public static int getShowdayCount(String showday){
}
}
Edit: What you do want and what you don't want
You dont need this in you if statement
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
When you want to print all the shows:
for (int i = 0; i < showdayCount.length; i++){
int showday;
if (i == 0){
showday = "Sunday
finish the if/else if statements
}
System.out.println("There is " + showDayCount[i] + " shows on " + showday);
}

Circular Doubly Linked List Program in Java (Homework Help)

Basically the program is supposed to create a "round table" of executives, with a chairman who cannot be changed. I kinda sorta almost know what I'm doing and I'm about halfway through my methods for inserting and removing executives, but I just tried to test my code to see how it was going and it gets errors as soon as I input the chairpersons information. Also, I'm not really sure at all how I would go about the removeByCorporation method in the ExecutiveList. I'm almost positive that method is nearly all incorrect and I'm just not how to remove a node in a circular doubly linked list like this.
*No need to help me with the printing methods, I simply haven't gotten to them yet.
tl;dr:
1) Why is it crashing right away?
2) I'm pretty sure my removeByCorporation method is totally wrong. If it is, any suggestions or help on how to fix it?
Here are the two classes I'm having trouble with, if you'd like to see the other ones let me know and I'll post them, but they're 99% getters and setters.
FIRST CLASS
public class ExecutiveList {
private ExecutiveNode chair;
ExecutiveNode cursor;
public ExecutiveList() {
}
public ExecutiveList (Executive chairperson) {
chair.setExecutive(chairperson);
chair.left = chair;
chair.right = chair;
}
public void insertLeftOfChair(Executive exec) {
ExecutiveNode newExec = new ExecutiveNode();
newExec.setExecutive(exec);
chair.setLeft(newExec);
}
public boolean insertRightOfExec (Executive exec, String target) {
cursor = chair;
ExecutiveNode newExec = new ExecutiveNode();
do { cursor = cursor.getLeft();
if (cursor.getExecutive().equals(exec)) {
newExec.setExecutive(exec);
cursor.getRight().setLeft(newExec);
newExec.setLeft(cursor);
newExec.setRight(cursor.getRight());
cursor.setRight(newExec);
return true;
}
else {
return false;
}
} while (cursor.getExecutive().getExecutiveName() != target);
}
public boolean insertLeftOfExec (Executive exec, String target) {
cursor = chair;
ExecutiveNode newExec = new ExecutiveNode();
do { cursor = cursor.getLeft();
if (cursor.getExecutive().equals(exec)) {
newExec.setExecutive(exec);
cursor.getLeft().setRight(newExec);
newExec.setRight(cursor);
newExec.setLeft(cursor.getRight());
cursor.setLeft(newExec);
return true;
}
else {
return false;
}
} while (cursor.getExecutive().getExecutiveName() != target);
}
public boolean removeTargetExec(String name) {
if (chair.equals(name)) {
return false;
}
else {
return false;
}
}
public int removeByCorporation(String corporation) {
int removed = 0;
cursor = chair;
do {
if (cursor.getExecutive().getCompanyName().equals(corporation)) {
cursor.setExecutive(null);
cursor.getLeft();
removed = removed + 1;
}
} while (removed > 0);
return removed;
}
public void printByCorporation(String corporation) {
}
public void printAllClockwise() {
}
public void printAllCounterClockwise() {
}
}
SECOND CLASS
import java.util.Scanner;
public class MeetingManager {
public static void main(String[] args) {
// scanner to read the users input
Scanner input = new Scanner(System.in);
// strings to pass information about the chairperson
String chairpersonName;
String chairpersonCompany;
// strings to pass information about executives other
// than the chairperson
String execName;
String execCompany;
String target;
// holds information on whether on not an operation
// was successful and how many executives were removed
// for the remove by corporation command.
boolean success;
int numRemoved = 0;
// prompts the user for information about the chairperson
// and sets it to an executive object name chairperson
System.out.println("Enter the name of the chairperson: ");
chairpersonName = input.next();
if (chairpersonName.length() < 1) {
System.out.println("Please enter a full name");
}
System.out.println("Enter the company of the chairperson: ");
chairpersonCompany = input.next();
if (chairpersonCompany.length() < 1) {
System.out.println("Please enter a full name");
}
Executive chairperson = new Executive(chairpersonName, chairpersonCompany);
// creates a new ExecutiveList object and passes information
// about the chairperson
ExecutiveList list = new ExecutiveList(chairperson);
// for loop to repeatedly print the menu and take instructions
// from the user until they choose to exit.
for (int i = 1; i > 0; i++) {
ShowMenu();
String option = input.next();
// error message for improper input
if (option.length() > 3) {
System.out.println("You can only enter one option");
}
// insert left of chairperson
else if (option.toUpperCase().equals("ILC")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
list.insertLeftOfChair(newGuy);
System.out.println("Insertion successful.");
}
// insert left of executive
else if (option.toUpperCase().equals("ILE")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
System.out.println("Enter the name of the target executive: ");
target = input.next();
success = list.insertLeftOfExec(newGuy, target);
if (success == true) {
System.out.println("Insertion successful.");
}
else {
System.out.println("The executive could not be inserted.");
}
}
// insert right of executive
else if (option.toUpperCase().equals("IRE")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
System.out.println("Enter the name of the target executive: ");
target = input.next();
success = list.insertRightOfExec(newGuy, target);
if (success) {
System.out.println("Insertion successful.");
}
else {
System.out.println("The executive could not be inserted.");
}
}
// remove target executive
else if (option.toUpperCase().equals("RTE")) {
System.out.println("Enter the name of the executive to remove: ");
execName = input.next();
success = list.removeTargetExec(execName);
if (execName.equals(chairpersonCompany))
list.removeTargetExec(execName);
if (success) {
System.out.println(execName + " has been removed from the meeting.");
}
else {
System.out.println(execName + " could not be found.");
}
}
// remove by corporation
else if (option.toUpperCase().equals("RBC")) {
System.out.println("Enter the name of the corporation to remove: ");
execCompany = input.next();
numRemoved = list.removeByCorporation(execCompany);
if (execCompany.equals(chairperson.getCompanyName())) {
System.out.println("Invalid command: cannot remove all employees from the chairperson's corporation");
}
else if (numRemoved < 1) {
System.out.println("That corporation could not be found and no executives were removed.");
}
else {
System.out.println(numRemoved + " executive(s) from " + execCompany + " have been removed from the meeting.");
}
}
// prints by corporation
else if (option.toUpperCase().equals("PBC")) {
System.out.println("Enter the name of a corporation to display: ");
execCompany = input.next();
list.printByCorporation(execCompany);
}
// prints all counter-clockwise
else if (option.toUpperCase().equals("PCC")) {
list.printAllCounterClockwise();
}
// prints all clockwise
else if (option.toUpperCase().equals("PCL")) {
list.printAllClockwise();
}
else if (option.toUpperCase().equals("EXT")) {
System.out.println("Terminating program...");
break;
}
// Error message
else {
System.out.println("Please select a valid option.");
}
}
}
// displays menu and prompts user for input
public static void ShowMenu() {
System.out.println("\nILC) Insert an executive to the left of the chairperson\nILE) Insert an executive to the left of a given executive\nIRE) Insert an executive to the right of a given executive\nRTE) Remove Target Executive");
System.out.println("RBC) Remove By Corporation\nPBC) Print By Corporation\nPCC) Print all in counter-clockwise order\nPCL) Print all in clockwise order\nEXT) Exit the program\n\nSelect a menu option: ");
}
}
Finally, thank you to anyone who gives any sort of suggestion or advice or actual help in any way shape or form. I know people get angry when they see homework questions for some reason because they think the student is asking them to "do their homework for me", but that's not what I'm doing. I'd simply like any advice or tips, I'm not asking you to just fill in the blanks for me and fix everything (not that I'd be opposed to it :P). Thanks.
In removeByCorporation method , you are just setting the executive to null , but considering this to be a doubly linked list , dont you think you need to set the references of the previous and next executive , so that the doubly linked list doesn't break .
The trick is to make sure that, on EVERY operation, you update the item being changed and the two others which reference it (quite handily in a doubly linked list, the two which reference it are also the two it references).
Check each of your methods, and ensure that in each one you are updating 4 fields per change - two in the subject, and one each in the two that are linked from the subject.

Categories

Resources