Struggling with my procedure in Java - java

I'm currently struggling to make my procedures to work. I'm having to do this all as objects This is what I have in my main file currently:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[6];
//myHotel[x] = new Room();
myHotel[0] = new Room();
myHotel[1] = new Room();
myHotel[2] = new Room();
myHotel[3] = new Room();
myHotel[4] = new Room();
String roomName = null;
String choice;
int roomNum = 0;
initialise(myHotel);
while ( roomNum < 5 )
{
System.out.println("Hotel Booking Options");
System.out.println("V: To View all rooms");
System.out.println("A: To Add a customer to a room");
choice = input.next();
if (choice.equals("V")) //views all the rooms
{
view(myHotel, roomName);
}
if (choice.equals("A")) //To add a customer to a room
{
System.out.println("Enter room number (0-5) or 6 to stop:" );
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
roomName = input.next();
myHotel[roomNum].mainName = roomName ;
//myHotel[roomNum].setName(roomName);
add(myHotel, roomName);
System.out.println(" ");
}
}
}
private static void initialise( Room hotelRef[] ) {
for (int x = 0; x < 5; x++ ) hotelRef[x].mainName = "empty";
System.out.println( "initilise ");
}
public static void view(Room myHotel[], Room roomName){
for (int x = 0; x <5; x++)
{
int z = 0;
Room Roomname = roomName;
myHotel[z]= Roomname;
if (myHotel[x].mainName.equals("empty"))
System.out.println("room " + x + " is empty");
else {
System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
//System.out.println("room " + x + " is occupied by "+ myHotel[x]);
}
}
}
private static void add(Room myHotel[], String roomName){
for (int x = 0; x <5; x++)
{
int z = 0;
String Roomname = roomName;
myHotel[z]= Roomname;
if (myHotel[x].mainName.equals("empty"))
{
System.out.println("room " + x + " is empty");
}
else {
System.out.println("room " + x + " is occupied by "+ myHotel[x]);
}
}
}
}
In my other .java file with the object variables:
public class Room {
String mainName;
//private String mainName;
int guestsInRoom;
public Room() {
mainName = "k";
System.out.println("made a room ");
}
public void setName(String aName) {
System.out.println("add name class method ");
mainName = aName;
}
public String getName() {
return mainName;
}
}
I'm not sure how to fix line 54 - view(myHotel, roomName); Sorry if my variable names are confusing and misleading...

Related

Ticket System + Timer

I'm currently working on an offline Jackpot system for fun, and i got stuck with the ticket problem.
Basically I want it to be (which seems to me like the best way to do it) so for every 10$ a user enters, you'll get 1 ticket. so let's say Jason deposits 250$, then he gets tickets 1-25, Bob deposits 100$ then he gets tickets 26-36. etc etc
then in the end it'd pick a random number and it'd pick a player that has that number in his range.
this is the current code:
public class Main {
private static int totalPlayers = 0;
private static int totalMoney = 0;
private static int playerDeposit = 0;
private static ArrayList<String> players = new ArrayList<String>();
private static ArrayList<Integer> botsMoney = new ArrayList<Integer>();
private static Timer timer;
private static Random random = new Random();
private static int playerMoney = 500;
private static String playerName;
private static double playerChance;
public static void main(String[] args) {
onUserEnter();
}
public static boolean onUserEnter(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter your name:");
playerName = scan.nextLine();
System.out.println("Money: 500$");
System.out.println("How much would you like to deposit?");
try{
playerDeposit = scan.nextInt();
}catch(NumberFormatException ex) {
System.out.println(playerDeposit + " is not a proper number!");
playerDeposit = 0;
return false;
}
if(playerDeposit <= 0) {
System.out.println("You can't deposit " + playerDeposit + "$");
return false;
}else if(playerDeposit > playerMoney){
System.out.println("You can't deposit more money than what you have!");
return false;
}
playerMoney -= playerDeposit;
System.out.println("You now have: " + playerMoney + "$");
players.add(playerName);
totalPlayers = players.size();
totalMoney += playerDeposit;
System.out.println(totalPlayers + " Players: " + players);
System.out.println("Total Pot: " + totalMoney + ", Your chances: 100%");
TimerTask tasknew = new TimerTask() {
#Override
public void run() {
}
};
timer = new Timer();
timer.schedule(tasknew, 20000);
botJoin();
return true;
}
public static boolean botJoin(){
botsMoney.add(5355);
int x = 0;
while(true){
int willBotJoin = random.nextInt(1000000000);
if(willBotJoin <= 2){
if(players.size() >= 10) {
break;
}
int moneyBotDeposits = random.nextInt(1100);
botsMoney.add(moneyBotDeposits);
double tickets = (double) moneyBotDeposits / 10;
x++;
players.add("Bob #" + x);
totalPlayers = players.size();
totalMoney += moneyBotDeposits;
System.out.println(totalPlayers + " Players: " + players);
playerChance = ((double) playerDeposit / totalMoney) * 100;
System.out.println("Total Pot: " + totalMoney + "$, Your chances: " + playerChance + "%");
}
}
botsPrecentage();
return true;
}
public static boolean botsPrecentage(){
for (int i = 1; i <= 9; i++){
double botPrecent = ((double) botsMoney.get(i) / totalMoney) * 100;
String botName = players.get(i);
System.out.println(botName + " has " + botPrecent + "%");
}
System.out.println(playerName + " has " + playerChance + "%");
return true;
}
Also I tried setting up a timer which I don't understand how, I've looked up Timer online but I just can't understand the explanations.

JavaFX Loop through array and find a match, otherwise try again

I have a GUI based e-store project. I read in a file and parse through it and saved it into an array.
The file format is like so: 11111, "title", 9.90
11111 is the book id, "title" is title, and 9.90 is the price.
I currently have 3 classes in my project. 1 class for Input/Output, 1 class for the Book store GUI code, and another for pop-up boxes when specific buttons are clicked.
In the GUI code, I check read the file into String[] fileArray and then loop through it until there is a match (with TextField input String bookIds = bookIdinput.getText())
I'm able to successfully get a match and go on with the rest of the code, but when there isn't a match, I get an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at windowDisplay.lambda$start$3(windowDisplay.java:###)
which is this line of code for(int i=0; i<fileArray.length; i++)
If there isn't a match, then it should show a pop-up box saying that bookID isn't found.
Below is some of the GUI code
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private String holdStr = "";
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
int qtyItems = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
// Loop through array to find match or no matches
for(int i=0; i<fileArray.length; i++)
{
// If there is a match in book ID
if (fileArray[i].equals(bookIDs))
{
double price = Double.parseDouble(fileArray[i + 2]); // Price is in the i+2 position
double discount = calculateDiscount(qtyItems);
totalAmount = calculatePrice(qtyItems, price);
itemInfoOutput.setText(fileArray[i] + " " + fileArray[i + 1] + " " + "$" + price + " " +
qtyItems + " " + discount + "%" + " " + "$" + df.format(totalAmount));
// Disable processItem Button if there is a match and enable confirmItem Button
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
}
}
if(matchFound == false)
System.out.println("No match found!");
});
}
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This methdod calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
This class reads the file and returns an array with the contents of that file (once split by the ", " delimitter).
public class bookStoreIO
{
// This method reads the input file "inventory.txt" and saves it into an array.
public static String[] readFile(String stringIn)
{
try
{
String nextLine;
String[] fIn;
// Read file
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
while((nextLine = br.readLine()) != null)
{
fIn = nextLine.split(", "); // Split when ", " is seen
if(stringIn.equalsIgnoreCase(fIn[0]))
{
br.close(); // Close file
return fIn; // Return array
}
}
}
// Just in case file isn't found
catch(IOException e)
{
System.out.println("File not found.");
}
return null;
}
I apologize if this seems messy, I'm still new to JavaFX and Java programming.
If you think more code is needed, please let me know!
EDIT: I improved some variable naming and removed the for loop. I'm still having trouble checking when there isn't a match.
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
private int itemQty = 0;
private int idBook = 0;
private String bookTitle = "";
private double bookPrice = 0.0;
private double discountAmount = 0.0;
private String resultOrder = "";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
if(matchFound == false)
System.out.println("not found");
});
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This method calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
I'm also having trouble saving
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
into an String or String array to print out a list of all the corresponding matches (along with their book ID, book Title, book Price, quantity, discount , and total price).
An example is shown below:
enter image description here
EDIT 2: The right box is the main GUI. The bottom left box is what shows up when a wrong book is entered (on the 2nd order). The top left is the length of the array.
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
for(int i=0; i<fileArray.length; i++)
System.out.println(fileArray[i]);
if(fileArray.length >= 3)
{
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
resultOrder = itemInfoOutput.getText();
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
resultOrder = idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount);
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
}
else
alertBox.confirmDisplay("Book ID " + idBook + " not in file");
});

Array values being set for everything (Java)

In my code below, I am having an issue where I add the customer name to one room, but instead it adds the customer to every room. I can't figure out what in my code the issue is. I have tried removing the procedure but that still produced the same problem.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice, custName = "";
int roomNum = 1;
String[] hotel = new String[12];
String[] customer = new String[12];
hotelInitialise(hotel);
custInitialise(customer);
while ( roomNum < hotel.length-1 ) {
for (int i = 0; i < hotel.length-1; i++) {
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("V: " + "View all rooms\n");
choice = input.next().toUpperCase();
if (choice.equals("A")) {
System.out.println("Enter room number(1-10)");
roomNum =input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
custName = input.next();
addNewBooking(hotel, custName);
System.out.println(" ");
}
if (choice.equals("V")) {
seeAllRooms(hotel, custName);
}
}
}
}
// When the program loads it will assign all the values of the array as being empty
private static void hotelInitialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++){
hotelRef[x] = "Room " + x + " is empty.";
}
System.out.println( "Welcome to the Summer Tropic Hotel.\n");
}
private static void custInitialise (String custRef[]) {
for (int i = 0; i < 11; i++) {
custRef[i] = ", no customer has occupied this room";
}
}
private static void addNewBooking(String hotel[], String customer) {
for (int x =1; x <11; x++) {
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
System.out.println("Room " + x + " is empty.");
else {
System.out.println("Room " + x + " is occupied by "+ customer);
}
}
}
private static void seeAllRooms(String hotel[], String customer) {
for (int i = 0; i < hotel.length-1; i++) {
int j=0;
String custName = customer;
hotel[j]= custName;
if (hotel[i].equals("Room " + i + " is empty."))
System.out.println("Room " + i + " is empty.");
else {
System.out.println("Room " + i + " is occupied by "+ hotel[j] + ".");
}
}
}
}
In addNewBooking method you have this line:
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
However hotel[x] has a value of "Room x is empty" e.g. hotel[1] is "Room 1 is empty" So the final check is becoming "hotel[x].equals(Room Room x is empty is empty.)" which is never equals to your hotel[x]
You have to change your code to
if (hotel[x].equals("Room " + x + " is empty."))
//do something there like add the booking

Why is may arrayList only showing one String?

java.util.*;
import java.io.*;
public class Sites
{
String country2, city2;
int days2, count = 0, time = 10;
double rate2, scost = 0;
public Sites(String province, String city, int days, double rate)
{
country2 = province;
city2 = city;
days2 = days;
rate2 = rate;
}
public void Sites()
{
{
Scanner scan = new Scanner(System.in);
try
{
while(count == 0)
{
BufferedReader file2 = new BufferedReader(new FileReader ("Sites.txt"));
while(file2.ready())
{
String cityS = file2.readLine();
String site1 = file2.readLine();
String cost1 = file2.readLine();
double cost1a = Double.parseDouble(cost1);
double tcost1 = cost1a * rate2;
String site2 = file2.readLine();
String cost2 = file2.readLine();
double cost2a = Double.parseDouble(cost2);
double tcost2 = cost2a * rate2;
String site3 = file2.readLine();
String cost3 = file2.readLine();
double cost3a = Double.parseDouble(cost3);
double tcost3 = cost3a * rate2;
String wiggle = file2.readLine();
if (cityS.equalsIgnoreCase(city2))
{
System.out.println("Province/Territory: " + country2 + "Number of Days Left: " + days2);
System.out.println("City: " + city2 + "Time: " + time + ":00");
System.out.println("");
System.out.println("Where would you like to go?");
System.out.println("1)" + site1);
System.out.println("Cost) " +cost1 );
System.out.println("");
System.out.println("2)" + site2);
System.out.println("Cost) " +cost2 );
System.out.println("");
System.out.println("3)" + site3);
System.out.println("Cost) " +cost3 );
System.out.println("");
System.out.println("4)Eat");
System.out.println("Cost) 25 ");
System.out.println("");
System.out.println("5)Rest");
System.out.println("Cost) 0 ");
System.out.println("");
int answer = scan.nextInt();
ArrayList<String> array = new ArrayList<String>();
Eat food = new Eat(answer,city2,rate2,array);
Descriptions sum = new Descriptions(site1,site2,site3,answer);
switch(answer)
{
case 1: time = time + 2;
scost = scost + tcost1;
sum.Description();
array.add(site1);
System.out.println("");
break;
case 2: time = time + 2;
scost = scost + tcost2;
sum.Description();
array.add(site2);
System.out.println("");
break;
case 3: time = time + 2;
scost = scost + tcost3;
sum.Description();
array.add(site3);
System.out.println("");
break;
case 4: time = time + 2;
scost = scost + (rate2*25);
food.Eat();
break;
case 5: time = time + 2;
System.out.println("You rested for a couple of hours.");
break;
}
if(time == 22)
{
days2 = days2 - 1;
time = 10;
}
if(days2 == 0)
{
count++;
for (int i = 0; i < array.size(); i++)
{
System.out.println("Thank you for using the tourist simulator. You spent " + scost + " and visited " +array.get(i));
}
}
}
}
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
You are re-declaring your ArrayList every iteration of your loop.
Try declaring your ArrayList above your declaration of the Scanner.
e.g.
Move
ArrayList<String> array = new ArrayList<String>();
To just above
Scanner scan = new Scanner(System.in);

Java Arrays not working

My Setup class:
import static java.lang.System.*;
import java.util.Scanner;
import java.io.*;
public class Setup
{
private String[] roomtype, custAddress, custName;
private int[] cPhone;
private double[] roomPrice;
private int[] roomNumber;
Scanner kb = new Scanner(in);
public Setup()
{
roomtype = new String[6];
custName = new String[6];
custAddress = new String[6];
roomPrice = new double[6];
cPhone = new int[6];
roomNumber = new int[6];
}
public void unoccupied()
{
String answer;
for (int c = 1; c<6; c++)
{
if(custName[c] == null)
{
out.println("Room" + roomtype[c] + " is not occupied.");
out.print("Would you like to assign a customer to this room?");
answer = kb.nextLine();
if (answer.contains("y"))
{
out.print("Which customer would you like to put in this room?");
answer = kb.nextLine();
roomtype[c] = answer;
}
}
}
}
public void addName(String[] custName)
{
for (int c = 1; c<6; c++)
{
if(custName[c] == null)
{
out.print("Add a name to customer " + c + ": ");
custName[c] = kb.nextLine();
}
}
}
public void addcPhone(int[] cPhone)
{
for (int p = 1; p<6; p++)
{
if(cPhone[p] == 0)
{
out.print("Add a cell phone number to customer " + p + ": ");
cPhone[p] = kb.nextInt();
}
}
}
public void addAddress(String[] custAddress)
{
for (int a = 1; a<6; a++)
if(custAddress[a] == null)
{
if(custName[a] == null)
{
out.print("Add an address to customer " + a + ": ");
custAddress[a] = kb.nextLine();
}
else
out.print("Add an address to " + custName + ": ");
custAddress[a] = kb.nextLine();
}
}
public String toString()
{
String receipt = "";
receipt += "Customer Name: " + custName ;
receipt += "Address: " + custAddress ;
receipt += "Phone number: " + cPhone ;
receipt += "Thanks for making your room reservation for Geek Speak with the Orozco Hotel!" ;
receipt += "We have you booked in room number " + roomNumber + ", which is a " + roomtype + "." ;
receipt += "Your charges for the convention will be $" + roomPrice + "." ;
receipt += "We hope you enjoy your stay with us and the convention.";
receipt += "The Orozco Hotel Staff";
return receipt;
}
}
And my driver class:
import java.util.Scanner;
import static java.lang.System.*;
public class Driver
{
public static void main(String[] args)
{
Scanner kb = new Scanner(in);
Setup[] customer = new Setup[5];
for(int i = 0; i<6; i++)
customer[i] = new Setup(custName, cPhone, custAddress);
Setup[] room = new Setup[5];
for(int i = 0; i<6; i++)
room[i] = new Setup(roomtype, roomPrice, roomNumber);
room[1].unoccupied();
}
}
Im trying to make 5 customer objects with custName, custAddress, and cPhone as parameters, and 5 room objects with roomPrice, roomtype, and roomNumber as parameters. I tried creating the objects with arrays, but I have no idea what I'm doing, as my teacher hasn't helped me at all this year. My driver class keeps returning the error "cannot find symbol" for the parameters in the customer and room objects. Any help to fix this code so that the objects hold the parameters is appreciated.
I think you need to reconsider your abstraction. These was a quick revamp to use a more OO approach. You can extend this idea by separating rooms from customer. You should have a hotel object be a collection of Rooms and customers.
import java.util.LinkedList;
public class Hotel{
LinkedList<Customer> customers;
public void addCustomer(Customer c){
customers.add(c);
}
public void removeCustomer(int roomNumber){
boolean flag = true;
for(int i = 0; i < customers.size() && flag; ++i){
if(customers.get(i).getRoomNumber() == roomNumber)
customers.remove(i);
flag = false;
}
}
public String toString(){
String s = "";
for(Customer c : customers)
s += c.toString() + "\n";
return s;
}
}
class Customer {
private String roomType;
private String address;
private String name;
private String phone;
private String price;
private int roomNumber;
public Customer(String rmTp, String addrss, String nm, String phn, String prc, int rmNm){
roomType = rmTp;
address = addrss;
name = nm;
phone = phn;
price = prc;
roomNumber = rmNm;
}
public int getRoomNumber(){ return roomNumber; }
public String toString(){
String receipt = "";
receipt += "Customer Name: " + name ;
receipt += "Address: " + address ;
receipt += "Phone number: " + phone ;
receipt += "Thanks for making your room reservation for Geek Speak with the Orozco Hotel!" ;
receipt += "We have you booked in room number " + roomNumber + ", which is a " + roomType + "." ;
receipt += "Your charges for the convention will be $" + price + "." ;
receipt += "We hope you enjoy your stay with us and the convention.";
receipt += "The Orozco Hotel Staff";
return receipt;
}
}

Categories