I have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.
Related
Can anyone help?
Choice 2 isn't working. It is suppose to display the employee ID when the user inputs the employee Name, but when the user enters the name nothing prints. The code has no errors.
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
//methods called from main
}
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
// search employee data
public static void search(String[] emplNames, int[]emplID) {
Scanner scan= new Scanner(System.in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = scan.nextInt();//input choice
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID= scan.nextInt();
for(int ID = 0; ID < emplID.length; ID++) {
if (searchID == (emplID[ID])){
System.out.println("Name: "+ emplNames[ID]);
}
}
}
// Choice 2 to enter name to display ID
else if(num == 2) {
System.out.println("Please enter Employee Name");
String searchName= scan.next();
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
}
else
System.out.println("Employee Not Found");
}
}
I copied and pasted your code and ran it on my machine. Yes, choice 2 was not working for me either.
Before reading your code completely my gut feeling was that the cause of failure was in using the Scanner class to get the name of the employee. I have had similar issues in the past and the best move is to learn to use the InputStreamReader and BufferedStreamReader objects.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
1: I didn't do anything to your main()
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
}
2: I didn't do anything to your employeeID() function
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
3: It's in your search() method where I first created the InputStreamReader and the BufferedReader:
public static void search(String[] emplNames, int[]emplID) {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = 0;
try {
num = Integer.parseInt(buff.readLine());
} catch (Exception e) {
e.printStackTrace();
}
4: Since choice 1 works fine, all I did was change your for loop to a for-each loop to make it easier to read.
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID = 0;
try {
searchID = buff.read();
} catch (Exception e) {
e.printStackTrace();
}
for (int i : emplID) {
if (searchID == i) {
System.out.println("Name: " + emplNames[i]);
}
}
5: Here is what I did to make your 2nd Option work. Again, get the String from user via BufferedReader object's readLine() method. Then, it was just letting your for-loop searching for a match. That's it. Afterward, I ran the program and tested it for all the names you had above, works fine.
} else if (num == 2) {
System.out.println("Please enter Employee Name");
String searchName = "";
try {
searchName = buff.readLine();
} catch(Exception e) {
e.printStackTrace();
}
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
} else {
System.out.println("Employee Not Found");
}
}
}
6: Yeah, Scanner has an issue where it either doesn't read the entire line or you need to flush the stream before getting the input. It caused a lot of problems for me in a bunch of easy programs. Then I switched to using the InputStreamReader and BufferedStreamReader combo. Just wrap them in try-catch blocks, and you're fine. Look into it, it will the behavior of your code and your life a lot easier.
7: I hope this was helpful.
so I'm just finishing up my first computer programming class ever and I'm having problems with my main method. I have 2 classes. The first class is homeClass.java and the other class is homeInventory.java. I'm just going to show you some of my homeInventory.java class unless you smarter ppl feel like it's prudent to have my other class. Basically, I'm having a problem with my else if statements. The program runs w/ the if statement, but won't completely run through the other options (else if). I must be missing something pretty apparent but I'll just see what you have to say on it. Thanks in advance!
public static void main(String[] args) {
ArrayList<homeClass> homes = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int i = 0;
int j = 0;
String option = "";
String answer = "";
String statusAnswer = "";
do {
System.out.println("Menu:");
System.out.println("1. Add a new home.");
System.out.println("2. Remove a home.");
System.out.println("3. Update home sale status.");
System.out.println("4. Exit");
System.out.print("Option chosen: ");
try {
while(true) {
if(scnr.hasNext()) {
option = scnr.next();
break;
}
}
}
catch (NoSuchElementException NSEE) {
continue;
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.print("Error, non-integer");
break;
}
try {
if(option.equals("1")) {
homes.add(addHome(scnr));
System.out.println("Home added.");
homes.get(i).getListing();
break;
}
else if (option.equals("2")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Remove this listing? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
homes.get(i).removeListing();
System.out.println("Home removed.");
}
else if (!answer.equalsIgnoreCase("Y")) {
System.out.println("Home not removed. Choose next option.");
}
}
break;
}
else if (option.equals("3")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Do you want to change the sale status? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter home sale status: ");
statusAnswer = scnr.next();
homes.get(i).setSaleStatus(statusAnswer);
homes.get(i).getListing();
}
}
break;
}
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.println("Error, option failed.");
}
} while(!option.equals("4"));
System.out.print("Do you want the home information stored in a file? Y or N: ");
answer = scnr.next();
String outputFileName = "C:\\Temporary\\Home.txt";
for (j = 0; j < homes.size(); ++j) {
String listing = homes.get(i).getListing();
if (answer.equalsIgnoreCase("Y")) {
try {
printToFile(listing, outputFileName);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("File printed to: " + outputFileName);
}
else {
System.out.println("File not printed.");
}
}
scnr.close();
return;
}
}
The problem I have encountered is as follows: I have created two array representing docking spaces for ships. The first array ship object be saved in the array and if there is no space then it will be added to a waiting list array. But when I remove an object from the first array the object from the waiting list array is not removed and added.
The dock can accommodate three sizes of ship; cargo, container and super-container. The rows are made up of 5 small and 3 medium and 2 large. A cargo ship (small) can berth in any available space. A container ship (medium) can berth in the medium space and large, but not in small spaces. A super-container can only fit in large space.
So if I enter shipName3 and Super-Container for example and there is already two Super-Container's it adds to the waiting list but when I remove a Super-Container from the dock it does not remove a ship from the waiting list and add it to the dock Can you help? Here's my dock method:
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
} else {
System.out.println("You cannot dock");
waitingList(name,size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
System.out.println("Enter ship's size to undock: ");
String size = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
//break;
///HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] == null) {
//Add ship to the dock
dock1[j] = new Ship(name, size);
System.out.println("Move ship from waiting list to dock 1");
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
}
public static void waitingList(String name, String size){
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < dock1.length; i++) { //waitingList?
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
break;
} else {
System.out.println("No space on waiting list, ship turned away");
return;
}
}
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
Ship class
public class Ship {
private String shipName;
private String shipSize;
public String getShipName() {
return shipName;
}
public void setShipName(String shipName) {
this.shipName = shipName;
}
public String getShipSize() {
return shipSize;
}
public void setShipSize(String shipSize) {
this.shipSize = shipSize;
}
public Ship(String shipName, String shipSize) {
this.shipName = shipName;
this.shipSize = shipSize;
}
}
I put my attempt in the undock method.
Please check your undock method in that you are removing from dock1 array and again you are adding to same object to dock1 array but there is no code to remove object from waitingList array simply update your loop in undock method as mentioned below
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
// break;
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j]=null;
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
I have changed inner loop iteration so it will loop to the size of waitingList array because we need to remove object from waitingList aray and add to dock1 array.Also i am runtime getting the shipname and shipsize from waitingList array so that it will add object from waitingList to dock1 array. I have tested code to my machine working here hope it will help you.
In your undock method, you remove the ship at the i'th position in dock1 array by setting it to null. This is ok but then you have a for loop that runs through all of the ships in dock1 looking for one with a null valued one. You aready know the one you just removed is null because you just set it to that value. Then you set it equal to a new ship that has the exact name and size of the one you removed (essentially putting the ship back). Instead, you want the for loop to traverse your list of waiting ships to find one that matches the space of the ship you just removed.
Replace:
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] == null) {
//Add ship to the dock
dock1[j] = new Ship(name, size);
System.out.println("Move ship from waiting list to dock 1");
break;
} else {
System.out.println("No space in dock1");
return;
}
}
with
for (int j = 0; j < waitingList.length; j++) {
if (waitingList[j].getShipSize() <= size) {
//Add ship to the dock
dock1[i] = waitingList[j];
System.out.println("Move ship from waiting list to dock 1");
return;
}
}
System.out.println("No space in dock1");
return;
My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda
The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop
Error: Could not find or load main class Disneyland
package com.Kassie$;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
try {
//Read from file
String[] aItems = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
.split("\n");
return aItems;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
for(int i = 0; i < storedValue.length; i++) {
if(storedValue[i][0].equals(name)) {
return (storedValue[i][1]);
}
}
return null;
}
public static void main(String[] args) {
char choice = ' ';
int totPrice = 0;
Scanner s = new Scanner(System.in);
String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
{"Minnie Mouse", "Toon Town"},
{"Goofy","Frontier Land"},
{"Pluto","Tomorrowland"},
{"Belle","Fantasyland"},
{"Jasmine", "Adventureland"}};
System.out.println("Do you like to know the "
+ "Disney Character's location(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Enter the name of the character");
String aName = s.next();
String location = findLocation(characterLocation,aName);
if( location != null) {
System.out.println("The character is located in " + location);
}
else {
System.out.println("Sorry! The character you are looking for "
+ "is not in park today");
}
}
String[] items = getItems();
String[] prices = getPrices();
choice = ' ';
System.out.println("Would you like to view the menu?(Y/N)");
choice = s.next().charAt(0);
if(choice == 'N' || choice == 'n') {
System.exit(0);
}
while(choice == 'Y' || choice == 'y') {
for(int i = 0; i < items.length; i++) {
System.out.println("Enter " + (i+1) + " for " + items[i]);
}
int option = s.nextInt();
System.out.println("Item : " + items[option-1]);
System.out.println("Price : " + prices[option-1]);
totPrice = totPrice + Integer.parseInt(prices[option-1]);
System.out.println("Do you want to order more(Y/N)?");
choice = s.next().charAt(0);
}
System.out.println("Are you an Annual Pass Holder?(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Your bill amount due : $" + ((double)totPrice -
((double)(totPrice*15))/100));
System.exit(1);
}
System.out.println("Your bill amount due : $" + totPrice);
}
}
You need to escape the dollar sign in your path.
To match a dollar sign, use "\$"
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public class AppointmentSchedule {
private static final int NUM_APPOINTMENTS = 6;
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] scheduled = new String[NUM_APPOINTMENTS];
Scanner consoleScanner = new Scanner(System.in);
int i;
String name;
for (int z = 0; z < NUM_APPOINTMENTS; z++) {
scheduled[z] = "";
}
System.out.println("To schedule an appointment, Please enter a time between 1PM to 6PM");
do {
i = consoleScanner.nextInt();
try {
if (i >= 1 && i <= 6) {
try {
if (scheduled[i] == "") {
System.out.println("Please enter your name.");
name = consoleScanner.next();
scheduled[i] = name;
System.out.println("Thank you " + name
+ ", you have been scheduled for " + i
+ " PM.\n");
System.out
.println("To schedule an appointment, Please enter a time between 1PM to 6PM");
} else {
throw new TimeInUseException();
}
} catch (TimeInUseException ex1) {
System.out.println(ex1.getMessage());
}
} else
throw new InvalidTimeException();
} catch (InvalidTimeException ex) {
System.out.println(ex.getMessage());
}
} while ();
consoleScanner.close();
}
}
What are some techniques to end the do while loop after scheduled[i] is filled up with 6 elements?
Would it look like: while (scheduled[z] != 6)?
Do this while(i<=5); this will let your loop run even when i=6 here i is the variable you keep incrementing
Just keep track of how many inputs the user has made. This can be done by declaring
int count = 0;
before the do...while loop and incrementing it from the body of the inner if:
if (scheduled[i - 1] == "") {
System.out.println("Please enter your name.");
name = consoleScanner.next();
scheduled[i - 1] = name;
System.out.println("Thank you " + name
+ ", you have been scheduled for " + i
+ " PM.\n");
count++; /* Note this */
System.out.println("To schedule an appointment, Please enter a time between 1PM to 6PM");
}
and finally, change the condition to
} while (count < 6);