I am trying to implement an Inventory program for shoes. What I am trying to do is give each shoe an id (productId) and a quantity of shoes that are in stock (ammountToPick). I want to be able to ask the user running the program to enter a shoe id to get the amount of that type of shoe that are left in stock (ammountToPick). My current problem with my program is that it is not returning anything and just keeps printing "invalid product id".
I have provided my code below:
public class Product {
private String productId = "";
private int ammountToPick = 0;
private int ammountToRestock = 0;
public Product (String productId, int ammountToPick){
this.productId = productId;
this.ammountToPick = ammountToPick;
}
public String getProductId() {
return productId;
}
public int getAmmountToPick() {
return ammountToPick;
}
}
public class Shoes extends Product{
public Shoes(String productId, int ammountToPick){
super(productId, ammountToPick);
}
}
import java.util.Scanner;
public class Inventory
{
private static String productId = "";
private int ammountToPick = 0;
private int ammountToRestock = 0;
public static final int MAX_ITEMS = 999999;
private static Product product [] = new Shoes[MAX_ITEMS];
public static void main (String args[]){
buildInventory();
getInventory();
}
public static void buildInventory(){
product[1] = new Shoes("shoe101", 19);
product[2] = new Shoes("shoe200", 1);
product[3] = new Shoes("shoe420", 9);
}
public static void getInventory() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the product id of the product you would like to pick: ");
String userinput = input.nextLine();
if(userinput.equals(productId)) {
System.out.println("there are" + product[1].getAmmountToPick() +"left");
}
else {
System.out.println("invalid product id ");
}
}
}
if(userinput.equals(productId)) {
System.out.println("there are" + product[1].getAmmountToPick() +"left");
}
else {
On the first line, you problem is that productId is set to an empty string at the top of the class. It should actually work if you just hit enter without entering an actual productId and userinput is "". But to make this work the way you want, get rid of your productId variable and check if userinput matches a productId of one of the items in your array
you need to do
userinput = ...; //this part is fine
for (Product p : products) {
if (userinput.equals(p.getProductId())) {
System.out.println('there are ' + p.getAmmountToPick() + " left");
}
}
Both the Product and Inventory classes have productId member variables. You're comparing userInput to the private static productIdin the Inventory class, which is an empty string.
I think you should be iterating through your inventory array looking for a match to the productId of a Product.
Here's one way to do it with an enhanced loop and no new methods:
boolean found = false;
for (final Product aProduct: product) {
if(userInput.equals(aProduct.getProductId())) {
System.out.println("there are" + aProduct.getAmmountToPick() +"left");
found = true;
break;
}
}
if(!found) {
System.out.println("invalid product id ");
}
I'd rename the product member variable to products so its intent is clearer. It would make the code above clearer as well.
Inventory, in the way you're using it, needs no productId. It should be deleted.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So everything works great in my program, but I read that making variable not private in class is a big mistake, because it can make problems with others part of big program.
Well I tried making HashMap airplane and flight private but I get error that "The field Airplane.airplane is not visible",which is of course true.
But how do I then make it visible in interface class?
Thanks in advance, I'm still learning and I got to this part in course.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
Airplane airplane = new Airplane();
flight flight = new flight();
interface_aerodrom ui = new interface_aerodrom(imeskanera,airplane,flight);
ui.start();
}
}
/ Airplane class
import java.util.HashMap;
public class Airplane {
HashMap<String,Integer>airplane;
private String id;
private int capacity;
public Airplane() {
this.airplane = new HashMap<String,Integer>();
}
public void add(String id, int capacity) {
this.id = id;
this.capacity = capacity;
this.airplane.put(id, capacity);
}
public String id() {
return this.id;
}
public int capacity() {
return this.capacity;
}
public String airplaneinfo() {
return this.id + "( " + this.capacity + " )";
}
}
/interface class
import java.util.Scanner;
public class interface_aerodrom {
private Scanner imeskanera;
private Airplane airplane;
private flight flight;
public interface_aerodrom(Scanner scanner, Airplane airplane,flight flight) {
this.imeskanera = scanner;
this.airplane = airplane;
this.flight = flight;
}
public void start() {
System.out.println("Airport panel\r\n"
+ "--------------------");
System.out.println();
while(true) {
System.out.println("Choose operation:\r\n"
+ "[1] Add airplane\r\n"
+ "[2] Add flight\r\n"
+ "[x] Exit");
String input = this.imeskanera.nextLine();
input = input.toLowerCase();
input = input.trim();
if(input.equals("x")) {
flight_service();
break;
}
else if(input.equals("1")) {
addairplane();
}
else if(input.equals("2")){
addflight();
}
}
}
public void flight_service() {
System.out.println("Flight service\r\n"
+ "------------");
while(true) {
System.out.println("Choose operation:\r\n"
+ "[1] Print planes\r\n"
+ "[2] Print flights\r\n"
+ "[3] Print plane info\r\n"
+ "[x] Quit");
String input = this.imeskanera.nextLine();
input = input.toLowerCase();
input = input.trim();
if(input.equals("quit")){
break;
}
else if(input.equals("1")) {
for(String name : this.airplane.airplane.keySet()) {
int numberofseats = this.airplane.airplane.get(name);
String list = name + "( " + numberofseats + " )";
System.out.println(list);
}
}
else if(input.equals("2")){
for(String name : this.flight.flight.keySet()) {
String value = this.flight.flight.get(name);
String list = name + value;
System.out.println(list);
}
}
else if(input.equals("3")) {
System.out.println("Give plane ID: ");
String planeid = this.imeskanera.nextLine();
if(airplanecontains(planeid)) {
int numberofseats = this.airplane.airplane.get(planeid);
System.out.println(planeid + "( " + numberofseats + " )" );
} else {
System.out.println("That plane is not in our database");
}
}
}
}
public void addairplane() {
System.out.println("Give plane ID: ");
String ID = this.imeskanera.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(this.imeskanera.nextLine());
this.airplane.add(ID, capacity);
}
public boolean airplanecontains(String ID) {
if(this.airplane.airplane.containsKey(ID)) {
return true;
}else {
return false;
}
}
public void addflight() {
System.out.println("Give plane ID: ");
String ID = this.imeskanera.nextLine();
if(airplanecontains(ID)) {
System.out.println("Give departure airport code: ");
String departure = this.imeskanera.nextLine();
System.out.println("Give destination airport code: ");
String destination = this.imeskanera.nextLine();
int seats = this.airplane.airplane.get(ID);
this.flight.flight.put(ID + " ( " + seats + " ) ",departure + "-" + destination);
}
else {
System.out.println("This plane is not in our database");
}
}
}
/ flight class
import java.util.HashMap;
public class flight {
HashMap<String,String>flight;
public flight() {
this.flight = new HashMap<String,String>();
}
public void add(String departure, String destination) {
this.flight.put(departure, destination);
}
}
Making a field private does not necessarily mean you can't share it. You can use a getter to return the HashMap.
private Map<String,Integer>airplane = new HashMap<>();
public Map<String,Integer> getAirPlaneMap() {
return airplane;
}
The reason being is that this hides implementation details and allows for future changes without affecting users of the class. Users don't need to know where the map comes from within your class. You could have retrieved it from some where yourself and the user wouldn't know.
You may also want to ensure a user can't change it. So you could do the following:
public Map<String,Integer> getAirPlaneMap() {
return Collections.unModifiableMap(airplane);
}
The above will prevent the user from adding or deleting map elements. But it won't prevent them from changing a retrieved object from the map unless that object is also immutable.
In general, setter and getters are the best way to allow users to set and retrieve values. And it is usually a good idea to make defensive copies of mutable items that they are retrieving to ensure that the retrieved values are consistent for all users during execution of the program.
I am trying to clean my code up by creating a class specifically for an array of information. It is basically like a storage for variables in case I need them later. Here is what I have so far:
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public static void setGender() {
Scanner input = new Scanner(System.in);
int[] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if(gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while (storeInts[0] < 1) {
storeInts[0]++;
}
}else if(gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
What I'm trying to accomplish here, is if the user types "boy" my code will store 1 in the index [0] of array storeInts[]. If the user types "girl" the index [0] will remain the value of 0.
If I need to refer to the user's gender later on, I want to be able to go back and figure out if they are a "boy" or a "girl" using the array.
I want to be able to called this array from any method within my code. I have already used this array in a complicated way and I would like to find a solution to make it easier.
Here is when I used it:
nameObject.setName(storeInts[0]);
I transferred the index [0] to the setName() method.
Here is the setName() method:
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
}else{
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
As you can see I created another array in the same manner as the previous one, but this one is to store Strings instead. Now back to what I was saying-- the parameter (int x) is the same value as storeInts[0]. This will tell me if the user is male or female. This value is sent to altInit() method when the user decides to try to continue without typing their name in first.
Here is the altInit() method:
public void altInit(int x) {
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")) {
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
When asked if they want to play games, they can type "yes" or "no." If the user types "no" as in they do not want to play games, then the program will print, "Consider this your last warning..." and then continue to the nextName() method in the previous class Gender. This also passes on that index[0] again in the array storedInts[].
Here is the nextName() method:
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
As you can see, if the user is that value of a male (or 1) then the program will print, "What is your name, sir?." If the value is a female (or 0), then the program will print, "What is your name, ma'am?"
This whole time I felt like the stored value of storeInts[0], was just leap frogging around until it was used... I want to prevent this by just creating a class with methods giving me the ability to call any value stored in that array whenever I need it. How do I create an array, store it in a method, and call it when needed?
As someone has requested, here is the entire code:
//Gender class
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public void setGender() {
Scanner input = new Scanner(System.in);
int [] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if (gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while(storeInts[0]<1){
storeInts[0]++;
}
} else if (gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
} else {
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public void nextName(int x){
if (x == 1) {
System.out.println("What is your name, sir?");
}else {
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
//Name class
package com.input;
public class Name extends Gender{
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
public void altInit(int x){
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")){
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
public void setName2() {
String name;
name = input.nextLine();
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You have failed to answer correctly. Try again:");
init();
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
}
How do I create an array, store it in a method, and call it when needed?
This is my first time posting on StackOverflow, but I have visited many times. I am taking a computer science class and I ran into a problem that I have not been able to resolve through research. The assignment is to create a NBATeam class with instance variables and constructors and a NBA client that receives parameters of the names of players from the user and passes them to an array in the first class.
So the problem that I ran into is when I run my program, and I enter player names and pass them to the array, the first array of names are deleted. The names entered into the most recent array are fine, however.
I apologize if my terminology is wrong I am still a newb!
Thank you so much for any help you can give me.
I will insert my code below. My problem is where it says [null]. Also I entered bob for the first team and brian for the second team but bob is in the second team's array.
Please help!
Create NBA team of Heats
Add a player to team Heats? (yes/no)
yes
Enter the name of the player:
bob
Add one more player to Heats?
no
Create NBA team of Spurs
Add a player to team Spurs? (yes/no)
yes
Enter the name of the player:
brian
Add another player to Spurs?
no
***Heat Wins!***
Heats[null]Wins: 4 Loses: 0
Spurs[bob]Wins: 0 Loses: 4
import java.util.*;
public class NBA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String ifAddPlayer, playerName = null;
//construct Team Heat
System.out.println("Create NBA team of Heats");
NBATeam heats = new NBATeam("Heats");
System.out.println("Add a player to team Heats? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
heats.addPlayer(playerName);
playerName = input.next();
System.out.println("Add one more player to Heats?");
ifAddPlayer = input.next();
}
//construct team Spurs.
System.out.println("Create NBA team of Spurs");
NBATeam spurs = new NBATeam("Spurs");
System.out.println("Add a player to team Spurs? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
spurs.addPlayer(playerName);
playerName = input.next();
System.out.println("Add another player to Spurs?");
ifAddPlayer = input.next();
}
playAGame(heats,spurs);
System.out.println(heats.toString());
System.out.println(spurs.toString());
}
public static void playAGame(NBATeam heats, NBATeam spurs) {
for(int game = 0; game < 7; game++){
double score = Math.random();
if (score < .5) {
heats.winAgame(spurs);
}
else{
spurs.winAgame(heats);
}
if(spurs.nWin()==4 || heats.nWin()==4) {
break;
}
}
if(spurs.nWin()>heats.nWin()) {
System.out.println("***Spurs Win!***");
}
else
System.out.println("***Heat Wins!***");
}
}
import java.util.Arrays;
public class NBATeam {
private String sTeamName;
private int nWin;
private int nLoss;
private int nPlayer;
private String [] playerArray = new String[nPlayer];
public NBATeam(String sTeamName) {
this.sTeamName = sTeamName;
nPlayer=0;
}
public int nWin() {
return nWin;
}
public int nLoss() {
return nLoss;
}
public String getTeamName(){
//gets team's Name
return sTeamName;
}
public String toString() {
return sTeamName + Arrays.toString(playerArray)+ "Wins: " + nWin +
" Loses: " + nLoss;
}
public void lossAgame() {
this.nLoss++;
}
public void winAgame(NBATeam team2) { //To win over the team
nWin++;
team2.setLoss(team2.nLoss()+1);
//teamB.lossAgame();
}
public int getLossNumber() {
return this.nLoss;
}
public void setLoss(int l) {
this.nLoss=l;
}
public int getWinNumber() {
return this.nWin;
}
public void setWin(int w) {
this.nWin=w;
}
public void addPlayer(String player) {
String temp[] = playerArray;
playerArray = Arrays.copyOf(temp, temp.length+1);
playerArray[nPlayer] = player;
nPlayer++;
}
public String[] getPlayerArray() {
return playerArray;
}
public void setPlayerArray(String[] playerArray) {
this.playerArray = playerArray;
}
}
You start with an initial value of null in playerName, and then you add the playerName before getting the value. This,
heats.addPlayer(playerName);
playerName = input.next();
is reversed. It should be
playerName = input.next();
heats.addPlayer(playerName);
And, you were consistent. This,
spurs.addPlayer(playerName);
playerName = input.next();
is likewise reversed. And should be
playerName = input.next();
spurs.addPlayer(playerName);
I would suggest you limit the visibility of your variables. If you had
String playerName = input.next();
heats.addPlayer(playerName);
it would limit the possibility of adding the player before you set it.
I'm still pretty new to java. Am trying to make a program that basically adds contacts to an array list. I have figured everything out as far as creating a new object and setting the name/number. As far as I can tell it's adding it to the array, however I'm not sure how I can display the array? I want to add a snippet of code that would display the array list after you add each contact.
Here is my contact class, not sure if I need the PhoneBook method or not for the array....
public class Contact {
String first; //first name
String last; //last name
String phone; //phone number
String PhoneBook; //array list???
public void PhoneBook(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public void setFirst(String first) {
this.first = first;
}
public void setLast(String last) {
this.last = last;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Contact makeCopy() {
Contact Contact = new Contact();
Contact.first = this.first;
Contact.last = this.last;
Contact.phone = this.phone;
return Contact;
} //end makeCopy
} //end class Computer
Here is my driver class...
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
Contact Contact = new Contact(); //make default Contact
Contact newContact;
String first; //first name
String last; //last name
String phone; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
Scanner scan = new Scanner(System.in);
Contact.setFirst("Default");
Contact.setLast("Default");
Contact.setPhone("Default");
while (add) {
System.out.println("Would you like to create a new contact? (Y/N)");
input = scan.nextLine();
if (input.equals("Y") || input.equals("y")) {
newContact = Contact.makeCopy();
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
phone = scan.nextLine();
ArrayList < Contact > PhoneBook = new ArrayList();
newContact.setFirst(first);
newContact.setLast(last);
newContact.setPhone(phone);
PhoneBook.add(newContact);
} else {
add = false;
System.out.println("Goodbye!");
break;
}
}
} //end main
} //end Class ComputerDriver
If just for printing, override the toString method of your Contact class, which will be like:
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
Then, in your main method, print all the contacts by doing:
for (Contact c : phoneBook) {
System.out.println(c);
}
Also, you should create the phoneBook, which is an ArrayList outside of your loop.
Your Contact class should be defined as:
public class Contact {
private String first; // first name
private String last; // last name
private String phone; // phone number
public Contact(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String getPhone() {
return phone;
}
public Contact makeCopy() {
return new Contact(first, last, phone);
}
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
}
And your main method should be:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Contact> phoneBook = new ArrayList<>();
while (true) {
System.out.println("Would you like to create a new contact? (Y/N)");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Enter the contact's first name: ");
String first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
String last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
String phone = scan.nextLine();
Contact contact = new Contact(first, last, phone);
phoneBook.add(contact);
for (Contact c : phoneBook) {
System.out.println(c);
}
} else {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
The compiler will give warning, most likely because of this:
String PhoneBook;
when you know that you also have
public void PhoneBook(String f, String l, String p)
and even more another PhoneBook
ArrayList < Contact > PhoneBook = new ArrayList();
try to use another variable name and function name to be safe and make sure they are different especially for
String PhoneBook;
public void PhoneBook(String f, String l, String p)
since they are under same class.
In terms of data structure, you have a wrong concept here. first is, this:
ArrayList < Contact > PhoneBook = new ArrayList();
should be outside the while loop so for whole your application, you will not replace your phone book after looping. to print them, later just use
for(int i = 0; i < phoneBook.size(); i++)
your printing
You just override toString() method of your Contact class, and in main() method, directly call your ArrayList's toString().
Here is my example:
package somepackage;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Inner> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Inner in = new Inner("name" + i, "address" + i);
list.add(in);
}
System.out.println(list.toString());
}
private static class Inner {
private String name;
private String address;
Inner(String name, String address) {
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "name:" + name + ", " + "address: " + address + "\n";
}
}
}
Screen outputs:
[name:name0, address: address0
, name:name1, address: address1
, name:name2, address: address2
, name:name3, address: address3
, name:name4, address: address4
, name:name5, address: address5
, name:name6, address: address6
, name:name7, address: address7
, name:name8, address: address8
, name:name9, address: address9
]
Ok, figured it out thanks to your guys help! I changed the if statement so you can now add a new contact, display the phone book, or quit. I also added phone number validation! Here is the updated code if anyone cares!
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
String first; //first name
String last; //last name
String phone = ""; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
boolean phoneValid; //boolean to validate phone number
Scanner scan = new Scanner(System.in);
ArrayList < Contact > PhoneBook = new ArrayList < > ();
while (add) {
phoneValid = false;
System.out.println("Type (N) to add a new contact, (D) to display your phonebook, or (Q) to quit!");
input = scan.nextLine();
if (input.equalsIgnoreCase("N")) {
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
while (!phoneValid) {
System.out.println("Enter the contact's phone number: XXX-XXX-XXXX");
phone = scan.nextLine();
if (phone.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
phoneValid = true;
break;
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
Contact contact = new Contact(first, last, phone);
PhoneBook.add(contact);
} else if (input.equalsIgnoreCase("Q")) {
add = false;
System.out.println("Goodbye!");
break;
} else if (input.equalsIgnoreCase("D")) {
for (Contact c: PhoneBook) {
System.out.println(c);
}
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
} //end main
} //end Class ComputerDriver
It sounds like you need to create some Getters. Most IDE's will do this for you.
For example, in your contact class add this:
public String getFirst(){ return first; }
Then do that for all of the items you want. When you want to print them out, set up a for each loop in your driver class like this:
for(Contact contact : PhoneBook){
System.out.println("Contact details: " + contact.getFirst() + " " + contact.getLast() + ", Phone #: " + contact.getPhoneNumber());
}
Alternatively, you could also create a method in you contacts class that takes the println contents from above and spits it out. For example:
public void printContactDetails(){ System.out.println("...");}
then in your for each loop call: contact.printContactDetails();
I am having trouble calling the methods on the main method. This is what I need to have in the main method:
Print the banner message
Get the product ArrayList
Get the product order from the user and check it exists in the product
ArrayList
If the product exists
Get the product price
Compute the product tax
Compute the total sale
Output the total sale
Else
Output "Product not found."
import java.util.ArrayList;
import java.util.Scanner;
public class Unit6ProblemSet {
public static void main(String[] args) {
bannerPrinter();
ArrayList<String> products = productBuilder();
Boolean productExists = getOrder(products);
if(productExists) {
double price = getPrice();
getTax(tax);
getTotal(saleTotal);
printTotal(saleTotal);
}
else {
System.out.println("Product not found.");
}
}
public static void bannerPrinter() {
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
public static ArrayList<String> productBuilder() {
ArrayList<String> products = new ArrayList<String>();
products.add("Headphones");
products.add("Pencils");
products.add("Pens");
products.add("Computers");
products.add("Videogames");
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String userStr = "";
System.out.println("Enter a product: ");
userStr = scnr.nextLine();
boolean productName = products.contains(userStr);
if (productName) {
System.out.println("True");
}
else {
System.out.println("False");
}
return productName;
}
public static double getPrice() {
double price = 0.0;
price = (Math.random() + 1) * 100;
return price;
}
public static double getTax(double price) {
double tax = 0.0;
tax = price * 0.10;
return tax;
}
public static double getTotal(double price, double tax) {
double saleTotal = 0.0;
saleTotal = price + tax;
return saleTotal;
}
public static void printTotal(double saleTotal) {
System.out.println("Your sale total is: " + saleTotal);
}
}
I am just having trouble calling the different methods in main.
You are on the right path.
bannerPrinter();
ArrayList<String> products = productBuilder();
The first line in your main method, bannerPrinter() calls your bannerPrinter method.
Now for your second call for productBuilder() you are basically getting a result back. Now using that result you can see if that product exists, get the product prices etc.
So in sort if you want to call a method from main all you have to do is use the method name to make that call.
For methods that have arguments like getOrder(ArrayList<String> products) you have to pass an argument to the method.
In your example it would be getOrder(products). that would call the method with the right argument and get a boolean result.
Also based on your recent edit when you call a method that has a return type, for example getOrder() you need to have a variable that get the result.
productBuilder() return a List<String> so you did this
ArrayList<String> products = productBuilder(); Which basically says, get my products and store them in my array list of products so I can use it.
Your other getters are doing something similar. You need to store the result and then use that to call your other methods.
I suggest you do some reading on Java in general, since this is a basic question. If this is a Java 101 type of class assignment re-read the first code chapters to get a better understanding of how methods and classes call each other.
There could be a possible issue in your getOrder method
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String userStr = "";
System.out.println("Enter a product: ");
userStr = scnr.nextLine();
//Move this after scanning user input
boolean productName = products.contains(userStr);
if (productName) {
System.out.println("True");
}
else {
System.out.println("False");
}
return productName;
}
In your main method, you keep calling the methods you need by passing the arguments they need and save their return result in a variable
public static void main(String[] args) {
bannerPrinter();
ArrayList<String> products = productBuilder();
Boolean productExists= getOrder(products); //getOrder needs arraylist and return boolean
//then check if the returned result is true i.e if product exists
if(productExists){
double price = getPrice();
//do other stuff, calcualte tax on price and then get total and etx
}
else{
//Print "product not found"
}
}