Add multiple values to arraylist from user input - java

I'm trying to add to my array list, then print out the list off all the programmers. Instead it just prints out the single programmer I just entered the details for. My question is. How do you correctly put the information entered into my Array list Programmer? Adding one array to another.
public Programmer(int id, String name, double pay, String time, int managerId) {
this.mId = id;
this.mName = name;
this.mPay = pay;``
this.mTime = time;
this.mManagerId = managerId;
this.mManager = null;
case 4:
String nameadd, time , manager;
double pay;
int manageradd;
System.out.println("Enter new car data:");
nameadd = in.getString("Name: ");
pay = in.getDouble("Wage: ");
time = in.getString("Part or Full Time: ");
manageradd = in.getInt("Manager ID: ");
p = ui.insert(nameadd, time, pay, manageradd );
System.out.println(p.getName() + ": WAGE: €" + p.getPay()+ " STATUS:" + p.getTime() + " MANAGER: " + p.getManager());
}
break;
And heres my View
public Programmer insert(String nameadd, String time, double pay, int manageradd) {
Programmer p;
p = new Programmer(0, nameadd, pay, time, manageradd);
return p;
}

At the start of your method or inside your class initialize the list.
List<Programmer> listOfProgrammers = new ArrayList<Programmer>();
Then you can add your programmers when they are created.
listOfProgrammers.add(p);

Related

java.lang.NullPointerException when setting value of attributes within a loop

Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.

How do I get data into a constructor from two different loops

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.

Need a way to associate strings with individual array elements

I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value
This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.
Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}

How Do I Get Customer Input To Display?

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.

Recording data, entering data in the command line, and limiting the length of integers

I have to write a program that models an employee. The employee has an employee number, a first and last name, an address consisting of a street, a city, a state, and a 5-digit zip code, and a hire date consisting of a month, a day, and a year. It must use an employee class, a name class, an address class, and a date class. Each class must record information that it entered by the user. Here is what I have written:
import javax.swing.JOptionPane;
public class AssignmentTen
{
public static void main (String[] args)
{
System.out.println();
int input1 = getInt ("Enter Employee Number:");
Employee e1 = new Employee(input1);
System.out.println("#" + e1.number);
String input2 = getString ("Enter Employee First Name:");
String input3 = getString ("Enter Employee Last Name:");
Name n1 = new Name(input2, input3);
System.out.println(n1.firstName + " " + n1.lastName);
String input4 = getString ("Enter Employee Street:");
String input5 = getString ("Enter Employee City:");
String input6 = getString ("Enter Employee State (Initials):");
int input7 = getInt ("Enter Employee Zip Code (5 Digits):");
Address a1 = new Address (input4, input5, input6, input7);
System.out.println(a1.eStreet + " " + a1.eCity + " " + a1.eState + " " + a1.eZipCode);
int input8 = getInt ("Enter Employee Hire Month (MM):");
int input9 = getInt ("Enter Employee Hire Day (DD):");
int input10 = getInt ("Enter Employee Hire Year(YYYY):");
Date d1 = new Date (input8, input9, input10);
System.out.println("Hire Date: " + d1.month + "/" + d1.day + "/" + d1.year);
}
public static int getInt(String paramString)
{
String str = JOptionPane.showInputDialog(paramString);
return Integer.parseInt(str);
}
public static String getString(String paramString)
{
String str = JOptionPane.showInputDialog(paramString);
return str;
}
}
class Employee
{
int number;
Employee(int newNumber)
{
number = newNumber;
}
}
class Name
{
String firstName;
String lastName;
Name(String first, String last)
{
firstName = first;
lastName = last;
}
}
class Address
{
String eStreet;
String eCity;
String eState;
int eZipCode;
Address(String street, String city, String state, int zipCode)
{
eStreet = street;
eCity = city;
eState = state;
eZipCode = zipCode;
}
}
class Date
{
int month;
int day;
int year;
Date(int eMonth, int eDay, int eYear)
{
month = eMonth;
day = eDay;
year = eYear;
}
}
However, I still have a few more things I need that I am not sure how to implement. My question is how can I:
Make the state string not display anything that is longer or shorter than two letters
Make the zip code variable in the Address class only display the first five characters of any inputs that are longer than five characters
Be able to store data for multiple Employees
Be able to specify how many employees information will be stored for in the command line
Store all of the information for a single employee in another class, and make objects for each employee containing all of their information
Any help or advice on how I can clean up my code will be greatly appreciated.
First of all, classes Date, Name, Address should be used as fields of Employee. Also consider variable names like zipCode instead of input7.
Be able to store data for multiple Employees
You can store Employees in a Collection, Set for instance:
Set<Employee> employess = new HashSet<>(); // field
...
employess.add(e1);
Be able to specify how many employees information will be stored for in the command line
int howmany = getInt ("Howmany emp you want to put");
for(int i = 0 ; i < howmany; i++) {
//invoke here extracted method getting all employee data
//example: employees.add(getEmployeeData());
}
Store all of the information for a single employee in another class, and make objects for >each employee containing all of their information
After putting Date,Name and Address into Employee problem will be solved i guess.
Make the zip code variable in the Address class only display the first five characters of >any inputs that are longer than five characters
int input7 = getInt ("Enter Employee Zip Code (5 Digits):"); //wrong varible name!
String zipCode = String.valueOf(input7);
if(zipCode.lenght() > 5) {
zipCode= zipCode.subString(0,4);
}
Make the state string not display anything that is longer or shorter than two letters
String input6 = getString ("Enter Employee State (Initials):");
if(input6.lenght != 2) {
input6 = "";
}

Categories

Resources