For some reason, after I add a pet named "Oliver" the main menu prints out twice with the "invalid choice" line along with it. I just need another set of eyes to look at it because I have been looking at it for hours on end and been fixing little mistakes to no avail.
The code when ran looks like this:
/*Welcome to the pet store.Type the letter to make your selection
A. List the pets in the store.
B. Age up the pets
C. Add a new pet
D. Adopt a pet
E. Quit
C
Please type in a name
Oliver
Please type in an age
22
Oliver has just been added to the store!
Welcome to the pet store.Type the letter to make your selection
A. List the pets in the store.
B. Age up the pets
C. Add a new pet
D. Adopt a pet
E. Quit
Invalid choice
Welcome to the pet store.Type the letter to make your selection
A. List the pets in the store.
B. Age up the pets
C. Add a new pet
D. Adopt a pet
E. Quit*/
Here is my main class code:
private static void mainmenu(){
System.out.println("Welcome to the pet store.Type the letter to make
your selection");
System.out.println("A."+" " + "List the pets in the store.");
System.out.println("B."+" " + "Age up the pets");
System.out.println("C."+" " + "Add a new pet");
System.out.println("D."+" " + "Adopt a pet");
System.out.println("E."+" " + "Quit");
MainPets.Getuserinput();
}
public static String Getuserinput(){
userinput=scan.nextLine();
return userinput;
}
public static void main (String [] args){
int pet3age;
String pet3name;
Pet Pet1=new Pet("Fido",3);
Pet Pet2=new Pet("Furball",1);
Pet Pet3=null;
int userinputint;
MainPets.mainmenu();
while(userinput.equals("A")||userinput.equals("B")||userinput.equals("C")||userinput.equals("D")||userinput.equals("E")){
switch(userinput){
case "C":
if (Pet3!=null&&userinput.equals("C")){
System.out.println("Sorry the store is full");
}
if(Pet3==null){
System.out.println("Please type in a name");
pet3name=scan.nextLine();
System.out.println("Please type in an age");
pet3age=scan.nextInt();
Pet3=new Pet(pet3name,pet3age);
System.out.println(pet3name + " has just been added to the store!");
}
MainPets.mainmenu();
break;
}
}
while(!userinput.equals("A")||!userinput.equals("B")||!userinput.equals("C")||!userinput.equals("D")||!userinput.equals("E")){
System.out.println("Invalid choice");
MainPets.mainmenu();
}
Here is the class with all the methods:
public class Pet {
String Name;
String AdoptionStatus;
int Age;
public Pet() {}
public Pet(String Name, int Age) {
this.Name = Name;
this.Age = Age;
}
public void SetName(String namesetup) {
Name = namesetup;
}
public String GetName() {
return Name;
}
public int GetAge() {
return Age;
}
public int ageincrease() {
return Age++;
}
public String Getadoptionstatus() {
return AdoptionStatus;
}
public void Setadoptionstatustonotadopted(int petnumber) {
AdoptionStatus="not adopted";
}
public void Setadoptionstatustoadopted(int petnumber){
AdoptionStatus="adopted";
}
}
It looks like you're trying to use static as much as possible for practice of what it does?
Anyway, see below for a minimal example of which you can build on (i.e. it will let you enter 'C' as many times as you want to 'add' new pets).
static String petname, petage;
public static void main(String[] args) {
initialText();
String userinput = userInput();
while (userinput.equals("A") || userinput.equals("B") || userinput.equals("C") || userinput.equals("D") || userinput.equals("E")) {
if(userinput.equals("C")){
System.out.println("Please type in a name");
petname = userInput();
System.out.println("Please type in an age");
petage = userInput();
Pet p = new Pet(petname, petage);
System.out.println(petname + " has been added to the store.");
}
else{
System.out.println("Option not configured yet");
//TODO - the rest of the options
}
initialText();
userinput = userInput();
}
}
public static void initialText() {
System.out.println("Welcome to the pet store.Type the letter to make your selection");
System.out.println("A." + " " + "List the pets in the store.");
System.out.println("B." + " " + "Age up the pets");
System.out.println("C." + " " + "Add a new pet");
System.out.println("D." + " " + "Adopt a pet");
System.out.println("E." + " " + "Quit");
}
public static String userInput(){
Scanner s = new Scanner(System.in);
return s.nextLine();
}
It's by no means perfect, just knocked it together very quickly to give you a chance to work on it.
Related
I am making a game and a the end of the game I want it to call the user by the name that they put in,, this is the code I have.
private static final Scanner console = new Scanner(System.in);
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation();
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation() {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt();
}
}
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
public static boolean Mascot() {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println("You, have sucsefully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
I want for it to at the end print * user's name*, you have successfully passed the third riddle.
but it needs to be able to weather the first name was kept, or if this sequence was used.
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
and if it has been activated it needs to use the new name.
Change return type of calledIt() to String and return realName from this method
Change return type of confirmation() to String. Initialize a String (String name = null). In the else part, assign the value returned from calledIt() to this string (String name = calledIt()). Return name.
In main, if the value returned from confirmation() is not null, update Name with this new value.
Pass the Name as input to Mascot method. For this, you have to update the Mascot method to accept a String as input.
You can pass the variable into confirmation() and calledIt() like this
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation(Name);
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation(String name) {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt(name);
}
}
public static void calledIt(String realName){
System.out.println("I knew it!");
System.out.print("whats your real name? ");
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
You could do the following change:
public static void main(String[] args) { // follow the prompts.//
System.out.println("Hello user! What is your name? ");
String name = console.nextLine();
System.out.println("Really? " + name + " is too weird to be a real name.");
System.out.print("Is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still don't believe you, so you will have to answer 3 riddles before you can continue to the game");
} else {
System.out.println("I knew it!");
System.out.print("Whats your real name? ");
name = console.nextLine();
System.out.println(
"" + name + " sounds like a real one, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
mascot(name);
System.out.println("Thank you for playing the demo");
console.close();
}
public static boolean mascot(String name) {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println(name + ", you have successfully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
The code below gets name and age of the animal and displays it. When I give 1 for dogs, for the first time the code runs correctly and when I give 1 for second time, i.e. when count is changed to 2, the code gets only the age and skips the name.
This happens for both Dog and Cat classes. And also the IDE shows that there is a resource leak problem near the Scanner scan. Please give me a solution
NOTE: This is the first time I'm programming in java, so I can't explain the problem clearly. So please excuse my flaws.
/**
*
*/
package pets;
import java.util.Scanner;
/**
* #author Karthic Kumar
*
*/
public class pets {
public static int total = 0;
public class Dog
{
int age;
String name;
int serial_no=1;
Scanner scan = new Scanner(System.in);
public void get_name()
{
System.out.println("enter the name of the dog: ");
name = scan.nextLine();
}
public void get_age()
{
System.out.println("enter the age of the dog: ");
age = scan.nextInt();
}
public void display()
{
System.out.println(serial_no+". the name of the dog is "+ name +" and his age is "+ age+"\n");
}
public void total_display()
{
System.out.println("total animals = "+total);
}
}
public class Cat
{
int age;
String name;
int serial_no=1;
Scanner scan = new Scanner(System.in);
public void get_name()
{
System.out.println("enter the name of the cat: ");
name = scan.nextLine();
}
public void get_age()
{
System.out.println("enter the age of the cat: ");
age = scan.nextInt();
}
public void display()
{
System.out.println(serial_no+". the name of the dog is "+ name +" and his age is "+ age);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int type,count=1;
pets object_1 = new pets();
pets.Dog dog = object_1.new Dog();
pets.Cat cat = object_1.new Cat();
System.out.println("press one for dog and two for cat and 3 for total");
while(count<=10)
{
System.out.println("\n"+count+". ");
type = scan.nextInt();
if(type == 1)
{
dog.get_name();
dog.get_age();
dog.display();
dog.serial_no +=1;
pets.total+=1;
}
if(type == 2)
{
cat.get_name();
cat.get_age();
cat.display();
cat.serial_no+=1;
pets.total+=1;
}
if(type==3)
{
dog.total_display();
}
if(type <=4 && type >=100)
{
System.out.println("enter correctly");
}
count++;
}
}
}
In order to fix your problem, you simply need to add a call to method nextLine() of class Scanner in your get_age() method in both class Cat and class Dog.
Here is the entire get_age() method from class Dog with the required addition.
public void get_age() {
System.out.println("enter the age of the dog: ");
age = scan.nextInt();
scan.nextLine(); // I added this line.
}
I have created a program in JAVA that has menu Options, 1 to 5. Option 4 being "Add student". Where it asks a 4 questions
Questions:
Please Enter student name:
Please Enter student course:
Please Enter student number:
Please Enter student gender:
After user has given these details, It will save into an array and ends the program. I am quite lost on how to save these details into an array.
This is my program where i tried to find a solution myself, But im relatively new to arrays and method myself.
public static void newstudent (String[] name,String[] course,int[] number,String[] gender)
{
}
public static void selection (int option) // Menu
{
switch (option)
{
case 1:
System.out.println("Display Student option");
break;
case 2:
System.out.println("Search Student");
break;
case 3:
System.out.println("Delete Student");
break;
case 4:
//code for adding new student
break;
case 5:
System.out.println("Exited");
break;
default:JOptionPane.showMessageDialog(null, "Invalid option! Please enter in the range from 1 to 5.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
//Start of Menu loop Statement
int option1 ;
do{
String option = JOptionPane.showInputDialog(null,"Enter your option:\n"+"\n"+"1. Display Students\n"+"2. Search Students\n" + "3. Delete Students\n"+"4. Add Students\n"+"5. Exit ","DMIT Students",JOptionPane.QUESTION_MESSAGE);
option1 = Integer.parseInt(option);
selection(option1);
}while(option1 <1 || option1 > 5);
// End of Menu Loop statement
}
}
i tried doing a for loop to add +1 to these array everytime a user inputs all these details but the for loop will be stuck in a infinite loop. Is there any suggestions that i can get? or easier solutions?
You shouldn't use arrays (the way you are using here) in the first place because you don't want to store the details of single student in four different places i.e. arrays. You can define a class Student with all the details you need and then it will be simple to add the details using class instances. Something like -
public class Student
{
private String m_name;
private int m_age;
private String m_course;
private String m_year;
private String m_section;
public Student( String name, int age, String course, String year, String section )
{
m_name = name;
m_age = age;
m_course = course;
m_year = year;
m_section = section;
}
public String getName()
{
return m_name;
}
public int getAge()
{
return m_age;
}
public String getCourse()
{
return m_course;
}
public String getYear()
{
return m_year;
}
public String getSection()
{
return m_section;
}
public String toString()
{
return "name: " + m_name + ", age: " + m_age +
", course: " + m_course + ", year: " + m_year +
", section: " + m_section;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int menuChoice = 4;
do {
System.out.println("\t\t\tStudent Record Menu");
System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
try {
System.out.println("Enter a choice: ");
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println("Full name:");
String name = input.nextLine();
int age = -1;
do {
try {
System.out.println("Age:");
age = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
continue;
}
} while (age <= 0);
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
System.out.println("Section:");
String section = input.nextLine();
Student student = new Student(name, age, course, year, section);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
}
} while (menuChoice<4);
}
}
The above code snippet is referred from here.
I am struggling to get this program to do exactly what the assignment asks. It throws a null pointer exception when trying to remove an added student. Also when I list the students, it shows null on everything.
-Code is fixed-
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> newStudents = new ArrayList<Student>();
System.out.println("Welcome to the Student Interface!.");
System.out.println("Please select a number from the options below \n");
while (true) {
// Give the user a list of their options
System.out.println("1: Add a student to the list.");
System.out.println("2: Remove a student from the list.");
System.out.println("3: Display all students in the list.");
System.out.println("0: Exit the student interface.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
addStudents(newStudents);
break;
case 2:
removeStudent(newStudents);
break;
case 3:
displayStudent(newStudents);
break;
case 0:
System.out.println("Thank you for using the student interface. See you again soon!");
System.exit(0);
}
}
}
public static void addStudents(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
Student newStudent = new Student();
System.out.println("Please enter first name: ");
String First_Name = input.next();
newStudent.setFirst_Name(First_Name);
System.out.println("Please enter last name: ");
String Last_Name = input.next();
newStudent.setLast_Name(Last_Name);
System.out.println("Please enter major: ");
String Major = input.next();
newStudent.setMajor(Major);
System.out.println("Please enter GPA: ");
String GPA = input.next();
newStudent.setGPA(GPA);
System.out.println("Please enter UIN: ");
String UIN = input.next();
newStudent.setUIN(UIN);
System.out.println("Please enter NetID: ");
String NetID = input.next();
newStudent.setNetID(NetID);
System.out.println("Please enter Age: ");
String Age = input.next();
newStudent.setAge(Age);
System.out.println("Please enter Gender: ");
String Gender = input.next();
newStudent.setGender(Gender);
if (newStudents.size() <= 10) {
newStudents.add(newStudent);
System.out.println("Student added\n");
} else {
System.out.println("\n Student interface is full!");
}
}
private static void displayStudent(ArrayList<Student> newStudents) {
for (Student e : newStudents) {
System.out.println(e);
}
}
private static void removeStudent(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
System.out.println("Please, enter the UIN to remove the Student: ");
String uin = input.nextLine();
for (Student e : newStudents) {
if (e.getUIN().equals(uin)) {
newStudents.remove(e);
System.out.println("Student removed");
break;
}
else {
System.out.println("Sorry, no such student with this " + uin + " " + "number exist");
}
}
}
Student Class:
package assignments;
public class Student{
private String First_Name;
private String Last_Name;
private String Major;
private String GPA;
private String UIN;
private String NetID;
private String Age;
private String Gender;
public String getFirstName()
{
return First_Name;
}
public void setFirst_Name(String value)
{
this.First_Name = value;
}
public String getLastName()
{
return Last_Name;
}
public void setLast_Name(String value)
{
Last_Name = value;
}
public String getMajor()
{
return Major;
}
public void setMajor(String value)
{
Major = value;
}
public String getGPA()
{
return GPA;
}
public void setGPA(String value)
{
GPA = value;
}
public String getUIN()
{
return UIN;
}
public void setUIN(String value)
{
UIN = value;
}
public String getNetID()
{
return NetID;
}
public void setNetID(String value)
{
NetID = value;
}
public String getAge()
{
return Age;
}
public void setAge(String value)
{
Age = value;
}
public String getGender()
{
return Gender;
}
public void setGender(String value)
{
Gender = value;
}
public String toString()
{
return "First Name: " + First_Name +
"\n Last Name: " + Last_Name +
"\n Major: " + Major +
"\n GPA: " +GPA+
"\n UIN: " + UIN +
"\n NetID: " + NetID+
"\n Age: " + Age+
"\n Gender: " + Gender;
}
public void createStudent(String first_Name2, String last_Name2, String major2, String gPA2, String uIN2, String netID2,
String age2, String gender2) {
first_Name2 = First_Name;
last_Name2 = Last_Name;
major2 = Major;
gPA2 = GPA;
uIN2 = UIN;
age2 = Age;
gender2 = Gender;
}
}
Your program runs about perfectly on my computer. Here’s an example run:
Welcome to the Student Interface!.
Please select a number from the options below
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
2
Please, enter the UIN to remove the Student:
13
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
1
Please enter first name:
o
Please enter last name:
v
Please enter major:
cs
Please enter GPA:
g
Please enter UIN:
79
Please enter NetID:
o
Please enter Age:
57
Please enter Gender:
m
Student added
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
3
Student [firstName=o, lastName=v, major=cs, gPA=g, uIN=79, netID=o, age=57, gender=m]
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
2
Please, enter the UIN to remove the Student:
79
Student removed
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
3
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
0
Thank you for using the student interface. See you again soon!
Potential issues in your program include: You have two Scanner objects on System.in, you may want to share just one. You don’t use the variable student_added. In my two cases the program didn’t report back to the user whether a student was removed or not. Your two TODO comments are obsolete and should be removed.
One of two reasons you'd get a NullPointerException on the remove operation. Either the ArrayList is null, or the object you are attempting to remove is null. Check for those.
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.