I am in an Object-Oriented Programming course in college and I have to use Java to start a program that will eventually incorporate a full on GUI by the end of the course. For the beginning of this project, I have to basically use message boxes to set up how a customer would order a sub to be delivered to their home.
Here's what I have so far:
This is the main class
import javax.swing.*;
//Here is the main class
public class Subs {
public static void main(String[] args) {
// Begin Main Method
char letter;
String input;
String input1, input2, input3, input4, input6, input8;
int input5, input7;
int subL; //length of sub in inches
int cup; //size of drink in ounces
JFrame frame = new JFrame("Message");
JOptionPane.showMessageDialog(frame, "Welcome to Famous Subs! ");
input1 = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");
input2 = JOptionPane.showInputDialog(frame, "Please Enter Your Address: ");
do {
input3 = JOptionPane.showInputDialog(frame, "What kind of sub would "
+ "you like? " +
"\n Turkey Club" +
"\n Philly" +
"\n Meatball" +
"\n Chicken Parm");
input4 = JOptionPane.showInputDialog(frame, "What type of bread? " +
"\n White" +
"\n Wheat" +
"\n Rosemary" +
"\n Italian Herb");
subL = getValidLength();
input6 = JOptionPane.showInputDialog(frame, "What would you like to "
+ "to drink? " +
"\n Water" +
"\n Soda" +
"\n Juice");
cup = getValidCup ();
input8 = JOptionPane.showInputDialog(frame, "Do you wish to continue?\n "+
"'y' or 'Y' for YES\n"+
"'n' or 'N' for NO\n");
Order firstOrder = new Order(input1, input2, input3, input4, input6, subL, cup);
JOptionPane.showMessageDialog(frame, firstOrder.toString());
letter = input1.charAt(0);
}
while (letter == 'Y'|| letter == 'y');
System.exit(0);
}
private static int getValidLength()
{
int s;
String input5;
do{
input5 = JOptionPane.showInputDialog(null, "What size of sub do you wish "
+ "to order? "+
"\n 6 inch"+
"\n 12 inch");
s = Integer.parseInt(input5);
} while (!(s==6 || s==12));
return s;
}
private static int getValidCup()
{
int c;
String input8;
do{
input8 = JOptionPane.showInputDialog(null, "What size drink? " +
"\n Small 12oz." +
"\n Medium 24oz." +
"\n Large 36oz.");
c = Integer.parseInt(input8);
}
while (!(c==12 || c==24 || c==36));
return c;
}
}
This is my subclass
//This is the class for the order
public class Order {
//creating my variables
private String Customer;
private String Address;
private String name;
private String bread;
private String drink;
private int length; //in inches
private int size; //in ounces
private double SubPrice;
private double DrinkPrice;
private double total;
//blank constructor
public Order(){}
//Create a constructor to hold variables
public Order (String Customer, String Address, String name, String bread, String drink, int subL, int cup){
this.Customer = Customer;
this.Address = Address;
this.name = name;
this.bread = bread;
this.drink = drink;
subL = length;
cup = size;
}
//create the getters and setters for the variables
public String getCustomer(){
return Customer;
}
public void setCustomer(String Customer){
this.Customer = Customer;
}
public String getAddress(){
return Address;
}
public void setAddress(String Address){
this.Address = Address;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getBread(){
return bread;
}
public void setBread(String bread){
this.bread = bread;
}
public String getDrink(){
return drink;
}
public void setDrink(String drink){
this.drink = drink;
}
public int getLength(){
return length;
}
public void setLength (int length){
this.length = length;
}
public int getSize(){
return size;
}
public void setSize (int size){
this.size = size;
}
public void setSubPrice (int subL, double SubPrice){
if (subL == 6)
SubPrice = 7.95;
else if (subL == 12)
SubPrice = 12.75;
}
public void setDrinkPrice(int cup, double DrinkPrice){
if (cup == 12)
DrinkPrice = 2.00;
else if (cup == 24)
DrinkPrice = 4.00;
else if (cup == 36);
DrinkPrice = 6.00;
}
public void setTotal(){
total = SubPrice + DrinkPrice;
}
#Override
public String toString(){
String grandOrder = "Greetings " + Customer +
"\nHere is your order: " +
"\n" + name +
"\n" + bread +
"\n" + drink +
"\nThe length of your sub is: " + length +
"\nThe size of your drink is: " + size +
"\nThe Price for your sub is: " + SubPrice +
"\nThe Price for your drink is: " + DrinkPrice +
"\nHere is your total: $" + calculateTotal(DrinkPrice, SubPrice) +
"\nThis will be delivered to: " + Address;
return grandOrder;
}
}
Everything runs just fine except the fact that the last box to show up returns all the string fields as null and the int and double variables as 0 or 0.0.
How do I return the values for what the user inputs on each dialog box? In addition, how do I get he customer's name and address to appear on this final screen? Thanks.
You never initialize fields of your Order. You call constructor without parameters public Order(){}. So you see the default values of the fields.
What you should do:
Be sure that you keep in a variable the value for the name of the client. (input = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");)
Be sure that you keep in variable user's input after "input = JOptionPane.showInputDialog(frame, "What kind of sub would "
+ "you like? " ...".
After get all inputs from the user, create Order object passing user's values
Order firstOrder = new Order(name, bread,drink,int subL, cup);
Change the constructor with parameters like that:
public Order (String name, String bread, String drink, int subL, int cup). You should not pass subPrice and drinkPrice because you Order class already know these values (see setdrinkPrice()). You determine the price of a cup based on the int cup. BTW, can you change the name of the method? Something like setDrinkPrice().
You never call setDrinkPrice() and setsubPrice()(should be setSubPrice(). You can do this when you calculate the total.
Start with these changes and if you have more problems ask .
Okay, a few things are going on here.
Order firstOrder;
firstOrder = new Order();
Can just be written as
Order firstOrder = new Order();
there's no need to do that on two lines. But, more importantly, you've not giving it any parameters, so Java is linking that to the empty constructor (the one that doesn't assign anything.) All of that nice constructor code you have isn't getting called.
To do that, you need to actually do something with those input fields you keep assigning (at the moment you're just ignoring them and writing over them); specifically, you should store them in local variables, and then pass them to the constructor like:
firstOrder = new Order(arg1, arg2, ...)
Also, Order isn't a subclass; it isn't extending anything. (Except Object, but we don't generally call something a subclass just for that.
input = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");
input = JOptionPane.showInputDialog(frame, "Please Enter Your Address: ");
On the first line above, you get the customer's name. then you call the second line, throwing away the customer's name without saving it anywhere.
Related
I have a homework assignment to Create an app that allows users to enter information about a collection of board games. The data entered by the user will be stored/accessed through a class. The steps I am given are to create the class, named BoardGame, for storing a collection of (analog or non-digital) board games with 8 fields. I then make a constructor that stores ONLY the first three fields. Then, for all fields, I create individual get and set methods, along with a toString method to print all the data for all the fields. Then within the main method there are 3 parts. Part 1, create an array called boardGames that has an array size of 4 (Right now I just have it set to 1 for testing). Create a loop to ONLY get the first three pieces of information. Part 2. AFTER the three basic pieces of the board game have been entered by the user, create a second loop to get the remaining five information from the user. Part 3. Once all the remaining data has been entered and stored by the user, create a third loop to print all the data in the array using the toString method (from the BoardGame class) for each object.
I think everything in BoardGame is set up correctly. I can also get Either step 1 or step 2 working with step 3. the issue is that I can't get step 1 AND step 2 to work at the same time. the Array either has the first 3 pieces of info or the last 5 pieces
I have tried making multiple constructors. I have tried a bunch of stuff that are probably all rookie errors XD
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
BoardGame[] boardGame = new BoardGame[1];
// Loop for first three peices of info
for (int i = 0; i < boardGame.length; i++) {
String gameName, publisherName, yearPublished;
System.out.print("What is the name of the board game? ");
gameName = scnr.nextLine();
System.out.print("Publisher name? ");
publisherName = scnr.nextLine();
System.out.print("Year published? ");
yearPublished = scnr.nextLine();
boardGame[i] = new BoardGame (gameName, publisherName, yearPublished);
}
// Loop for remaining peices of info
for (int i = 0; i < boardGame.length; i++) {
String genre;
double price;
int minPlayerNum, maxPlayerNum, playTime;
System.out.print("How much does " + boardGame[i].getGameName() + " cost? ");
price = scnr.nextDouble();
System.out.print("What is the minimum number of players for " + boardGame[i].getGameName() + "? ");
minPlayerNum = scnr.nextInt();
System.out.print("What is the maximum number of players for " + boardGame[i].getGameName() + "? ");
maxPlayerNum = scnr.nextInt();
System.out.print("What is the game genre? ");
scnr.nextLine();
genre = scnr.nextLine();
System.out.print("How long on average does it take to play " + boardGame[i].getGameName() + " (in minutes)? ");
playTime = scnr.nextInt();
boardGame[i] = new BoardGame (price, minPlayerNum, maxPlayerNum, genre, playTime);
}
for (int i = 0; i < boardGame.length; i++) {
System.out.println(boardGame[i].toString());
System.out.println();
}
}
}
public class BoardGame {
// Fields
private String gameName;
private String publisherName;
private String yearPublished;
private double price;
private int minPlayerNum;
private int maxPlayerNum;
private String genre;
private int playTime;
// Constructor 1
public BoardGame(String gameName, String publisherName, String yearPublished) {
this.gameName = gameName;
this.publisherName = publisherName;
this.yearPublished = yearPublished;
}
// Constructor 2
public BoardGame(double price, int minPlayerNum, int maxPlayerNum, String genre, int playTime) {
this.price = price;
this.minPlayerNum = minPlayerNum;
this.maxPlayerNum = maxPlayerNum;
this.genre = genre;
this.playTime = playTime;
}
// Get Methods
public String getGameName() {
return gameName;
}
public String getPublisherName() {
return publisherName;
}
public String getYearPublished() {
return yearPublished;
}
public double getPrice() {
return price;
}
public int getMinPlayerNum() {
return minPlayerNum;
}
public int getMaxPlayerNum() {
return maxPlayerNum;
}
public String getGenre() {
return genre;
}
public int getPlayTime() {
return playTime;
}
// Set Methods
public void setGameName(String gameName) {
this.gameName = gameName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public void setYearPublished(String yearPublished) {
this.yearPublished = yearPublished;
}
public void setPrice(double price) {
this.price = price;
}
public void setMinPlayerNum(int minPlayerNum) {
this.minPlayerNum = minPlayerNum;
}
public void setMaxPlayerNum(int maxPlayerNum) {
this.maxPlayerNum = maxPlayerNum;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setPlayTime(int playTime) {
this.playTime = playTime;
}
// Prints the data FIX_ME if min and max number of players is the same, only print one number
public String toString() {
return "Game name: " + gameName + "\nPublisher Name: " + publisherName +
"\nYear Published: " + yearPublished + "\nPrice: " + price +
"\nMinimum number of players: " + minPlayerNum + "\nMaximum number of players: "
+ maxPlayerNum + "\ngenre: " + genre + "\nPlay time: " + playTime;
}
}
`
Depending on how I have it set up, either the first three won't have an assigned value, or the last 5 won't. It is currently set up in a way that makes the first three data pieces null.
In your second loop, instead of overriding the current BoardGame object by a new one like in your current code:
boardGame[i] = new BoardGame (price, minPlayerNum, maxPlayerNum, genre, playTime);
You should retrieve the BoardGame already stored in your array by the first loop, and call your setters on it:
boardGame[i].setPrice(price);
boardGame[i].setMinPLayerNum(minPlayerNum);
//etc...
Like so, you won't be overriding/replacing any values, you are just adding properties to the already created object.
What I have is a two snippets of code. The question I have in particular is about my dropCourse method within the student driver. Everything in my code seems to work fine except when I drop a course it does not drop the courses credits. For example, if I drop a course named "Computer101" which had four credits, it will remove "Computer101" From the schedule, but will not remove the "4" credits when I choose option 5 to print the total credits. So if we have a full schedule of:
Computer101 in position 0 worth 4 credits
Physics105 in position 1 worth 4 credits
Art101 in position 2 worth 4 credits
Chem101 in position 3 worth 4 credits
And I decide to drop Computer101 from the schedule, all other classes will move up in their position in the array as they are supposed to, when printing the schedule that class will no longer show up and when it is searched for it will not be found, but the amount of credits it was worth will still be there. I feel like the solution is right in front of me, but I am so burned out I am not seeing it. I would really appreciate any help and I hope I was clear with what I am asking.
Here is where my dropCourse method will be found:
public class Student
{
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
final int MAX_CREDITS = 18;
int courseNumber = 0; //start out with no courses
int totalCredits;
final int SIZE = 6;
String [ ] schedule = new String [SIZE];
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
System.out.println("The course has been added!");
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 6 courses
{
System.out.println("You have exceeded 6 courses.");
}//end courseNumber
}//addCourse
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
public int searchCourse(String courseName)
{
String course;
boolean flag = false;
int index = 0;
while(index < courseNumber && flag == false)
{
String extract = schedule[index].substring(0,6);
if (extract.contains(courseName) == true)
{
flag = true;
}
else
{
index++;
}
}
if (flag == false)
{
return -1;
}
else
{
return index++;
}
}
public void dropCourse(String courseName)
{
int found;
found = searchCourse(courseName);
int index = 0;
if (found == -1)
{
System.out.println("Course not in schedule");
}
else
{
if (found == 5)
{
courseNumber = courseNumber -1;
}
else
{
for (index = found; index < courseNumber; index ++)
{
schedule[index] = schedule[index + 1];
}
courseNumber = courseNumber -1;
System.out.println("The course has been dropped!");
}
}
}
public int totalCredits()
{
System.out.println("The total credits are " + totalCredits);
return totalCredits;
}
}//end class Student
This is where my menu that works with the above code is:
//This is a Driver program to test the external Class named Student
import java.util.Scanner;
public class TheMenu //BEGIN Class Definition
{
//**************** Main Method*************************
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
//Data Definitions:
//Instance Data
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
String courseName;
int courseCredits;
int menu = 0;
//Initialize first Student
name = "Florence Welch";//look her up
id = "7777";
street = "777 Heaven Street";
city = "Witchville";
state = "NY";
zip = "12345";
major = "Arts";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
while (menu < 6)//begin while for menu options
{
System.out.println("1. Add a course ");
System.out.println("2. Search for a course");
System.out.println("3. Drop a course");
System.out.println("4. Print out a student's schedule");
System.out.println("5. Print out total credits");
System.out.println("6. Exit");
System.out.println("Enter an option: ");
menu = scan.nextInt();
if (menu == 1)//option to add course
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);//uses method to store course information in array
}
else if (menu == 2)//option to search for course
{
int x;
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
student1.searchCourse(courseName);
x = student1.searchCourse(courseName);
if (x == -1)//course is not found if value returns -1
{
System.out.println("Course not found");
}
else
{
System.out.println("Course found in position " + student1.searchCourse(courseName));//shows user the position of course
}
}
else if (menu == 3)//will drop course from users schedule
{
System.out.println("Please enter the course you wish to drop: ");
courseName = scan.next();
student1.dropCourse(courseName);
}
else if (menu == 4)//displays the users schedule
{
System.out.println(name + "'s Schedule:\n\n");
student1.displaySchedule();
}
else if (menu == 5)//will display users credits for semester
{
student1.totalCredits();
}
else
{
System.out.println("Enjoy your semester!");//option 6 will exit program
}
}
}
}
I'm creating a Java array of queues program to represent patients in a doctor array. It lets me add nodes in data structure but when I try to print it out it blows up on me. Here is the method
static boolean [] openflag = new boolean[6];
static queue [] Clinic = new queue[6];
static String [] Doctor = {"Doctor 1", Doctor 2", "Doctor 3","Doctor
4","Doctor 5","Doctor 6"};
final static String HEADING = "The clinic moniter of Dylan Rychlik";
static int MAX = 6;
public static void Listpaitents()
{
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is notaviable");
}
else{
Paitent[] array = Clinic[queuechoice -1].toArray();
//int size = Clinic[queuechoice -1].getSize();
int limit = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 1; x <= limit; x++) {
out += array[x-1].Print() + "\n";
// System.out.println(array[x-1] + "\n");
}
JOptionPane.showMessageDialog(null,out);
}
}
Here is the toarray() method in queue class.
public static Paitent[] toArray()
{
int x = Length;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = Length; ((Current != null) && (x >= 1));x--)
{
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
}
return Array;
}
And finally, here is the paitent class
public class Paitent {
protected static String name;
protected static String telephone;
protected static int ID;
//Creates a constructor for a paitent object
public void paitent()
{
name = "";
telephone = " ";
ID = 0;
}
//updates the country object
public void update(Paitent thisThing)
{
name = thisThing.name;
telephone = thisThing.telephone;
ID = thisThing.ID;
}
//asks for user input for country objects
public void input(int i)
{
String PatronHeading = "Country Data Entry";
String entername;
int enterID;
String enterphone;
entername = JOptionPane.showInputDialog(null, "Please Enter the name of
paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterphone = JOptionPane.showInputDialog(null, "Please Enter the telephone
number for paitent #" + i +": ", PatronHeading,
JOptionPane.QUESTION_MESSAGE);
String PNumberString = JOptionPane.showInputDialog(null, "Please Enter the
ID for paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterID = Integer.parseInt(PNumberString);
name = entername;
telephone = enterphone;
ID = enterID;
}
//prints the results
public String Print()
{
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number " +
telephone + " ID " + ID;
return outputString;
}
//gets and sets the PCI in order to sort them
}
Any help? Tried several tactics to fix it and nothing seems to be working. There a lot of code so if you need the full code please let me know!
A problem with your code is that you are using static variables. This means they can only ever have one value
so change
protected static String name;
protected static String telephone;
protected static int ID;
to
protected String name;
protected String telephone;
protected int ID;
edit and clean up your code
I am a very amateur student programmer who has made a code that sells a user items and then calculates the tax of that item by asking what state the user lives in. It is a very simple code given my lack of experience with programming. Unfortunately, I made the mistake of writing this code without thinking ahead.
This program is actually my final project for my class. Because of that, there are requirements that I have to meet which I am currently having difficulties with. I have completed almost all of the requirements, but have noticed that some are not yet completed. Some requirements I am missing are...:
1 specialized constructer (I have never understood how to do this efficiently, and am having doubts as to if this is still even possible, given my code)
1 accessor and 2 modifiers (Same thing as constructor, how do I do this correctly with my given code?)
Some sort of formated output using printf (Maybe can be used to round the total price? Too bad I don't fully understand it)
Here is my [extremely inefficient] code itself:
import java.util.Scanner;
public class Tax_Calculator {
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
//variables
double taxPrice = 0;
double totalPrice = 0;
int choice = 0;
double rawCost = 0;
System.out.println("Hello! Welcome to the new 7/11 online ordering device.");
System.out.println("We're low on supplies, so only pick one.");
System.out.println("");
//menu
String [][] menu = {
{"(1) Pizza - $4.99"," (6) Slurpee - $0.79"},
{"(2) Cigarettes - $7.99"," (7) Hotdog - $1.99"},
{"(3) Coffee - $2.99", " (8) Doritos - $2.99"},
{"(4) Mountain Dew - $1.49", " (9) Water - $1.29"},
{"(5) Ice cream - $2.49", " (10) Muffin - $0.99"},
};
//prints menu
for (int e = 0; e < 5; e++)
{
System.out.println(menu[e][0] + "\t"+ menu[e][1]);
System.out.print("");
}
System.out.println("");
System.out.println("Enter the number of the item you want: ");
//user chooses item off of menu
int userInputMenu = in.nextInt();
if (userInputMenu == 1)
{
choice = 1;
System.out.println("You chose the pizza for $4.99.");
rawCost = 4.99;
}
if (userInputMenu == 2)
{
choice = 2;
System.out.println("You chose the cigarettes for $7.99.");
rawCost = 7.99;
}
if (userInputMenu == 3)
{
choice = 3;
System.out.println("You chose the coffee for $2.99.");
rawCost = 2.99;
}
**Continues all the way to userInputMenu == 10**
System.out.println("Now to calculate the tax, please enter the state you are currently in: ");
String userInputState = in.next();
//what state is the user in?
if (userInputState.equals("Alaska") || userInputState.equals("Delaware") || userInputState.equals("Montana") || userInputState.equals("New Hampshire") || userInputState.equals("Oregon"))
{
taxPrice = 0.0;
System.out.println("Luckily, the sales tax in " + userInputState + " is 0, so your final price is " + rawCost);
}
if (userInputState.equals("Colorado"))
{
taxPrice = 0.029;
totalPrice = ((taxPrice * rawCost) + rawCost);
System.out.println("The sales tax in " + userInputState + " is only " + taxPrice);
System.out.println("That means that the total price of your item is "+ totalPrice);
}
**Also continues for all 50 states**
//thank you
System.out.println("");
System.out.println("Thank you for shopping at the new online 7/11.");
System.out.println("Thank you come again.");
}
Just asking for some thorough explinations on how I can meet my missing requirements.
Also, how can I have it so when the user is inputting a state, the program can read it as either "MARYLAND" or "maryland"?
Have you read anything on object oriented programming? This is a great situation to use it, since you have a superclass of 'items', subclasses of those items 'coffee' 'slurpee' etc. Also is the customer able to purchase more than one item at a time and then find the total with tax?
I attempted to code this. You could take it further based on inputs from others on SO or your needs. It could be good start up for you. Add try/catch to handle exceptions:
Class to hold Menu objects:
public class Menu {
private int id;
private String item;
private double Price;
public Menu(int id, String item, double price) {
super();
this.id = id;
this.item = item;
Price = price;
}
public int getId() {
return id;
}
public String getItem() {
return item;
}
public double getPrice() {
return Price;
}
#Override
public String toString() {
return "Menu [id=" + id + ", item=" + item + ", Price=$" + Price + "]";
}
public boolean validateMenu(int id) {
if (id == this.id) {
System.out.println("You chose the " + item + " for " + Price);
return true;
}
return false;
}
}
Class to hold State objects:
public class State {
private String message;
private String state;
private double taxPrice;
public State(String state, double taxPrice, String message) {
this.state = state;
this.taxPrice = taxPrice;
this.message = message;
}
public String getMessage() {
return message;
}
public String getState() {
return state;
}
public double getTaxPrice() {
return taxPrice;
}
#Override
public String toString() {
return "State [taxPrice=" + taxPrice + ", state=" + state
+ ", message=" + message + "]";
}
public boolean validateState(String state) {
if (state.equalsIgnoreCase(this.state)) {
System.out.println(this.message.replace("userInputState", this.state) + this.taxPrice);
return true;
}
return false;
}
}
Tax_Calculator
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Tax_Calculator {
public static void main(String[] args) throws Exception {
Scanner in = null;
Tax_Calculator tc;
Menu menu = null;
State state = null;
double taxPrice;
double totalPrice;
System.out
.println("Hello! Welcome to the new 7/11 online ordering device.");
System.out.println("We're low on supplies, so only pick one.");
System.out.println("");
tc = new Tax_Calculator();
boolean continueFlag = true;
while (continueFlag) {
tc.printMenu();
System.out.println("");
System.out.println("Enter the number of the item you want: ");
in = new Scanner(System.in);
int userInputMenu = in.nextInt();
for (Menu menu2 : tc.menuList)
if (menu2.validateMenu(userInputMenu)) {
menu = menu2;
break;
}
if (menu == null)
System.out.println("Please choose a valid number! \n");
else
continueFlag = false;
}
System.out.println("");
System.out
.println("Now to calculate the tax, please enter the state you are currently in: ");
in.nextLine();
String userInputState = in.nextLine();
for (State state2 : tc.stateList)
if (state2.validateState(userInputState)) {
state = state2;
break;
}
taxPrice = state.getTaxPrice();
totalPrice = (1 + taxPrice) * menu.getPrice();
System.out.print("That means that the total price of your item is ");
System.out.printf("%.2f", totalPrice);
System.out.println("");
System.out.println("Thank you for shopping at the new online 7/11.");
System.out.println("Thank you come again.");
in.close();
tc.destroy();
}
private List<Menu> menuList = null;
private List<State> stateList = null;
Tax_Calculator() {
initMenu();
initState();
}
private void destroy() {
menuList = null;
stateList = null;
}
private void initMenu() {
menuList = new ArrayList<Menu>();
menuList.add(new Menu(1, "Pizza", 4.99));
menuList.add(new Menu(2, "Cigarettes", 7.99));
menuList.add(new Menu(3, "Coffee", 2.99));
}
private void initState() {
stateList = new ArrayList<State>();
stateList.add(new State("North Dakota", 0.05,
"The sales tax in userInputState is "));
stateList.add(new State("Arizona", 0.05,
"The sales tax in userInputState is "));
stateList.add(new State("Maine", 0.05,
"The sales tax in userInputState is "));
}
private void printMenu() {
for (Menu menu : menuList)
System.out.println(menu);
}
}
Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)