How to add data into array in another class in Java? - java

[EDIT: I've solved the problem. I just need to make the arrays static. I can't believe I didn't of that. Thanks for everyone's help!]
I have a bookstore program where people can buy a maximum of 5 different books. Once they choose a title, it will be added to an array for the invoice later. Choosing the titles and putting it into the array is in 2 different classes. Just for trial, I'm buying 2 books: Athletics and Autosport.
Expected output:
You bought 2 book(s)!
1) Athletics Weekly Magazine
2) Autosport Magazine
Edited List.java: I've tried both things. First is changing to i-1
In SportsMag.java:
import java.util.Scanner;
public class SportMag extends Magazine{
Scanner scan = new Scanner(System.in);
public void title() {
System.out.println("");
System.out.println("What do you want to buy?");
System.out.println("1. Athletics Weekly");
System.out.println("2. Autosport");
int choice = scan.nextInt();
List l = new List();
if (choice==1) {
l.totalbooks(1);
l.booknames(1,"Athletics Weekly", "Magazine");
} else {
l.totalbooks(1);
l.booknames(1,"Autosport", "Magazine");
}
System.out.println("Do you want to go back to menu? (Yes/No)");
String back = scan.next();
if (back.equalsIgnoreCase("Yes")) {
BookType b = new BookType();
b.bookMenu();
}
if (back.equalsIgnoreCase("No")) {
l.printInvoice();
}
}
}
In List.java (where I print the invoice):
public class List {
static int total=0;
public void totalbooks(int num) {
total+=num;
}
String[] bookname = new String[5];
String[] booktype = new String[5];
static int a=0;
public void booknames(String newBookName, String newBookType) {
bookname[a]=newBookName;
booktype[a]=newBookType;
a++;
}
public void printInvoice() {
System.out.println("You bought "+total+" book(s).");
for (int i=0; i<total; i+=1) {
System.out.println((i+1)+") "+bookname[i]+" "+booktype[i]);
}
}
}
The output for this is:
You bought 2 book(s).
1) null null
2) Autosport Magazine
I also tried using ArrayList:
In SportMag.Java:
//same as above, only a little difference here
List l = new List();
if (choice==1) {
l.totalbooks(1);
bookname.add("Athletics Weekly");
} else {
l.totalbooks(1);
bookname.add("Autosport");
}
In the List.java:
ArrayList<String> bookname = new ArrayList<String>();
public void printInvoice() {
System.out.println("You bought "+total+" book(s).");
for (int i=0; i<total; i+=1) {
System.out.println(bookname.get(i));
}
}
I got an error in the SportMag.java that says bookname cannot be resolved. A quick fix offered was to create a local variable bookname but then it won't go to the array in List.java
I haven't learned about ArrayList so I'm not really sure what to do here.
I also tried making another version where everything is in the main method and only calls the methods in other classes to display the titles, not actually scanning the input in the other methods. I did this so that no objects die after each functions. The main became really long tho.
I don't know if this works fine for 2 books because I can't loop since everything is in the main.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BookType b = new BookType();
List l = new List();
b.bookMenu();
int booktypechoice = scan.nextInt();
if (booktypechoice ==1) {
Magazine mag = new Magazine();
mag.magtype();
int magtypechoice = scan.nextInt();
if (magtypechoice==1) {
SportMag smag = new SportMag();
smag.title();
int smagchoice = scan.nextInt();
SportMag sportmag = new SportMag();
if (smagchoice==1) {
l.totalbooks(1);
l.booknames("Athletics Weekly", "Magazine");
System.out.println("Do you want to go back to menu? (Yes/No)");
String goback = scan.next();
if (goback.equalsIgnoreCase("Yes")) {
b.bookMenu();
}
if (goback.equalsIgnoreCase("No")) {
l.printInvoice();
}
} else {
l.totalbooks(1);
l.booknames("Autosport", "Magazine");
System.out.println("Do you want to go back to menu? (Yes/No)");
String goback = scan.next();
if (goback.equalsIgnoreCase("Yes")) {
b.bookMenu();
}
if (goback.equalsIgnoreCase("No")) {
l.printInvoice();
}
}
} else {
//all the other book choices goes here.
//It's really long, but it's just like sportmag up there
}
}
}
}
How do I input the book names into the array and have it displayed correctly?

I think you are having trouble with the scope of the variable List l. You create this variable inside the function title and you work with it, inserting in it the product the client requested. But then, where does the variable go from there? It just dies out at the end of the function. This object should be in a scope that will exist for as long as it is interesting.
For exemple, you can transform this variable into a property of your main class. It can be even a static class. You should find the better way to preserve your List object. As it is, it is dying as soon as the title function ends.

Related

Java Encapsulation with arrays

So I have two classes one is called bag the other is called TestBag. The goal is to ask the user what they want: to add or remove, and show what they have in the cart.
I'm kinda new to encapsulation, and I don't know how to get the user input and put it in the add method and get that to go the the cart string to show what the user has in the cart. This is what I have so far. I'm doing the add part first before the remove.
bag class:
import java.util.Arrays;
class bag {
private String[] cart = new String[5];
private int add;
public String[] getcart(){
return Arrays.copyOf(cart, getcart().length);
}
public int getAdd(){
return add;
}
public void setAdd(int newValue){
add = newValue;
}
public void setcart(String [] cart){
cart = cart;
}
}
TestBag:
import java.util.Scanner;
public class TestBag {
public static void main(String[] args) {
bag obj = new bag();
System.out.println("Enter one of the following commands:");
System.out.println("1 - add");
System.out.println("2 - remove");
System.out.println("3 - exit");
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\"");
int choice =input.nextInt();
while (choice != 3) {
if(choice == 1) {
System.out.println("What do you want to add? ");
for (int i = 0 ; i < obj.setAdd.length; i++ ) {
obj.setAdd[i] = input.nextInt();
}
System.out.println("Here's whats in your cart: ");
printArray(obj.getcart());
}
else if(choice == 2) {
//remove
}
else if(choice == 3) {
//...exit program
}
else{
System.out.println("Enter \"1\", \"2\", \"3\"");
choice = input.nextInt();
}
}
}
}
Thank you for sharing your code. Looking at your bag class, you're trying to achieve encapsulation through data hiding:
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
However, declaring the getters and setters that way exposes the variables you declared as private in the first step. Well, the getters are just fine since one really has to see the contents of the cart and the number of items in the cart. The setters are not fine. It's like declaring your variables as public since through the setters, you allow them to be modified at any time.
The main point of encapsulation through data hiding is to restrict access to the class's variables to selected methods. Here's how I'd go about it:
public class Bag{
//Assuming that the bag has a dynamic size, a list would be appropriate here
public List<String> items;
public Bag(){
items = new ArrayList<String>();
}
//This modifies the contents of the bag. The modification is restricted
//through one of the methods (adding an item into the bag)
//that are really part of the task.
public void add(String item){
items.add(item)
}
public List<String> getItems(){
return new ArrayList<String>(items);
}
public int getNumberOfItems(){
return items.size();
}
}

How can i edit an array from another part subProgram

Before someone says 'We're not solving your homework, ask your teacher' I only get programming on a Wednesday and this is not homework. It's an extra task that i asked for
Anyways i'm trying to create a program that i can Input a game's name and price then display the titles of all the games(which are in an array) and then another option to display the total price of all games
The issue i'm having is that i can't add to the array(Hard to explain so here's my code )
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Java {
public static void main(String[] args) {
Java.mainMenu();
}
public static void mainMenu() {
// ArrayList titleArray
// PrimitiveArray priceArray
int choice = 0;
String again = "";
String[] gameTitle = new String[0];
Scanner user_input = new Scanner(System.in);
System.out.println(" Main Menu");
System.out.println("");
System.out.println("1) Enter Game Details");
System.out.println("2) Display Titles in Order");
System.out.println("3) Display Total Price");
System.out.println("");
System.out.println("Choice : ");
choice = user_input.nextInt();
if (choice ==1){
gameDetails(gameTitle);
} else if (choice ==2) {
displayTitles(gameTitle);
} else if (choice ==3) {
}
}
public static void displayTitles(String[] gameTitle) {
// Choice 2
System.out.println(Arrays.toString(gameTitle));
}
public static void gameDetails(String[] gameTitle) {
//Choice 1
String addGameTitle;
double addGamePrice;
Scanner user_input = new Scanner(System.in);
System.out.println("Enter the game Title : ");
addGameTitle = user_input.next();
Java.mainMenu();
}
}
So i run this and put 1 in, it asks me for the Title of the game i enter it but it doesn't get added to the array? Is it because of the way that i am Passing the array?
try doing an array list!
List<array length> <name> = new ArrayList<array length>
<arrayname>.add(<location in array>) = <something>
<arrayname>.add(<location in array>) = <something>
Unfortunately, you will need to have a set length of the array beforehand, which means you can't add to it after you have filled the capacity of the array.
hope this helps!
(Note: I'm relatively new to java myself so I could be forgetting something, or misremembering.)

Java - Added user input to ArrayList, needs to be separated by variables in another ArrayList

My template opens with a menu of options. When the user chooses option 1, it asks them to input a number teamNumber. One must instantiate the class Team, then it writes it to an arraylist.
If there is at least one number in numberList, the user can select option 2. It asks them to input any of the numbers from the arraylist and searches it. If the number they input is found, then you input the team member. It will write the input to a private arraylist located in class TeamMember.
I'm very close to figuring this all out except for one problem. It seems that regardless of which stored team number I input after choosing option 2, the team member I add to teamList is added to ALL team numbers, not just the one I want it to be added to. So, say in option 1 I added a team 1 and a team 2. Then in option 2, I type 1 and proceed to enter the member. It ends up adding the team member to both team 1 and 2. Is there a way to fix this? I tried a few options but can't seem to wrap my head around it.
public class Main {
public static void main(String[] args) {
int choosing;
Scanner scan = new Scanner(System.in);
String input;
int teamNumber;
boolean stayInLoop;
ArrayList<Team> numberList = new ArrayList<Team>();
do {
stayInLoop = true;
System.out.println("1. Add a new team");
System.out.println("2. Add a new team member");
System.out.println("3. View teams");
input = scan.nextLine();
if (input.equals("1")) {
System.out.println("Enter a team number:");
teamNumber = scan.nextInt();
scan.nextLine();
Team addTeam = new Team(teamNumber);
numberList.add(addTeam);
}
if (input.equals("2")){
boolean foundIt = false;
boolean valid = true;
System.out.println("Team number:");
teamNumber = scan.nextInt();
scan.nextLine();
for (int a = 0; a < numberList.size() && foundIt == false; a++){
Team addTeam = numberList.get(a);
if (addTeam.findTeam() == teamNumber) {
foundIt = true;
System.out.println("Enter first name of team member:");
String teamMemberFirstName = scan.nextLine();
System.out.println("Enter first initial of last name:");
char firstInitialLastName = scan.nextLine().charAt(0);
TeamMember inputTeamMember = new TeamMember(teamMemberFirstName, firstInitialLastName);
inputTeamMember.addMember(inputTeamMember, valid = true);
int teamSize = (inputTeamMember.size(valid = true));
System.out.println("Team " + teamNumber + " has " + teamSize + " members!");
}
}
if (foundIt == false) {
System.out.println("Try again.");
}
}
}while (stayInLoop == true;)
}}
TeamMember:
public class TeamMember {
//the code provided in the task had teamList set to private, so I'm assuming it's required to be that way. I added static in order to eventually be able to call it with a method to view the team in option 3. But if the only solution involves changing the list to public, then so be it.
private final String teamMemberFirstName;
private final char firstInitialLastName;
private static ArrayList<TeamMember> teamList = new ArrayList<>();
public TeamMember(String teamMemberFirstName, char firstInitialLastName) {
this.teamMemberFirstName = teamMemberFirstName;
this.firstInitialLastName = firstInitialLastName;
}
public int addMember(TeamMember member, boolean valid) {
valid = teamList.add(member);
return teamList.size();
}
public static int size(boolean valid) {
return teamList.size();
}
}
teamList is static, hence shared by all instances of TeamMember. Remove the static keyword.

if statement not working properly with variables from another method

I'm totally new to Java (4 days old), and I'm trying to create my first program after watching a few YouTube videos.
Basically I'm trying to make a (guess my number game). I've created a function/method to get a random number and another function/method to get a user inputted number (both from another class called random)
I've then called these 2 values in my main method/function to be compared in a (if) statement but every time I run the program I get the same output.
Output:
Welcome to The Guessing Game
*******Version 1.1**********
Enter your name please :
john
Nice to meet you john
Ok then....let's go over the rules
I'm gonna pick a number between 1 and 10
You have 4 atempts to guess otherwise i win
Good luck!!!!
Ok i've chosen the number between 1 and 10
take a guess :
2
You are correct!!!!
I seem to get the same output every time ;-(
Sorry in advance for asking a maybe straight forward question.
(Do remember I'm a newbie and many thanks for your help.)
shaz
Below is a copy of my code:
public class GuessMain {
public static void main(String[] args) {
introduction intro = new introduction();
intro.welcome();
introduction enterName = new introduction();
enterName.userName();
introduction rules = new introduction();
rules.explainRules();
// introduction getN = introduction();
// getN.getName();
introduction glMessage = new introduction();
glMessage.goodluckMessage();
random pickRandNumber = new random();
pickRandNumber.pickRandom();
random readyMessage = new random();
readyMessage.readysteadyGo();
random guessNumobj = new random();
guessNumobj.getGuessnum();
random getNumobj = new random();
getNumobj.getNumber();
}
if (guessNumobj.getGuessnum() == getNumobj.getNumber()){
System.out.println("You are correct!!!!");
}else if (guessNumobj.getGuessnum() > getNumobj.getNumber()){
System.out.println("Too high!!!!");
}else if (guessNumobj.getGuessnum() < getNumobj.getNumber()){
System.out.println("Too low!!!!");
}
}
}
import java.util.Scanner;
public class introduction {
private String name;
public void welcome() {
System.out.println("Welcome to The Guessing Game");
System.out.println("*******Version 1.1**********");
}
public void userName() {
System.out.println("Enter your name please :");
Scanner userInput = new Scanner(System.in);
name = userInput.nextLine();
System.out.println("Nice to meet you " + name);
}
public void explainRules() {
System.out.println("Ok then....let's go over the rules");
System.out.println("I'm gonna pick a number between 1 and 10");
System.out.println("You have 4 atempts to guess otherwise i win");
}
public String getName() {
return this.name;
}
public void goodluckMessage() {
System.out.println("Good luck!!!! ");
}
}
import java.util.Random;
import java.util.Scanner;
public class random {
private int number;
private int guessNum;
public void pickRandom () {
Random getRandom = new Random();
for (int counter = 1; counter <= 1; counter++) {
number = getRandom.nextInt(10); //this stores the random number[(10){1 to 10}] in (number;) vairiable
}
}
public void readysteadyGo(){
System.out.println("Ok i've chosen the number between 1 and 10");
System.out.println("take a guess :");
Scanner scanOb = new Scanner(System.in);
guessNum = scanOb.nextInt();
}
public int getNumber(){
return this.number;
}
public int getGuessnum(){
return this.guessNum;
}
}
random is a class, and you can have any number of instances (objects) of that class. Each instance contains its own versions of number and guessNum. If you create two new random() objects, object1 and object2, and you do something that assigns to object1.number, and then you look at the value of object2.number, it will not be the value that you assigned to object1.number.
That's the problem with your code. You create one object pickRandNumber, and then call a method that sets pickRandNumber.number. You create another object readyMessage and then call a method that asks for user input and then sets readyMessage.guessNum. Then you create two new objects, and try to get the number and guessNum from the new objects. Those new objects have their own number and guessNum values, which you haven't set to anything--you've set the values of number and guessNum in different objects.
The solution is to rewrite main() to use the right objects. So after
random pickRandNumber = new random();
pickRandNumber.pickRandom();
that will set pickRandNumber.number, and if you want to retrieve that number, use something like:
if (pickRandNumber.getNumber() == ....)

Creating and Returning Values from an ArrayList in Java

I'm working on an assignment for a low-level java class. I have it mostly finished, but I'm stuck on how to use an ArrayList. There are two classes, the second one (PizzaMaker) is the client. I need to initialize an ArrayList in the first class and then add three items to it via user input from the client. I know how to initialize the ArrayList, but I'm having problems adding items to the list. When I run the code I have now, it returns with empty brackets [ ] or null.
I'm not expecting someone to do my homework for me, but a clue as to where I'm going wrong with this code would be helpful.
import java.util.*;
public class Pizza {
private String brand;
private int size;
private ArrayList<String> toppings = new ArrayList<String>();
public Pizza(String brand, int size) {
this.brand = brand;
this.size = size;
}
public void changeBrand(String brandName) {
brand = brandName;
}
public void changeSize(int pizzaSize) {
size = pizzaSize;
}
public void addTopping(String topping) {
toppings.add("topping");
}
public String getPizzaInfo() {
String result = "You want a "+ size +" inch pizza made by: "+ brand +" with these
toppings:" + toppings;
return result;
}
}
public class PizzaMaker {
public static void main( String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
System.out.println(newPizza.getPizzaInfo());
}
public static String getBrand() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a brand name: ");
String brandName = kb.nextLine();
return brandName;
}
public static int getSize() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a size: ");
int pizzaSize = kb.nextInt();
kb.nextLine();
return pizzaSize;
}
public static String getTopping() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter topping: ");
String topping = kb.nextLine();
return topping;
}
public static boolean getAgain() {
return true;
}
}
You need to call addTopping. Eg, newPizza.addTopping(topping). Also, correct the addTopping method. Replace toppings.add("topping") with toppings.add(topping);
And I am sure you need to put more effort to learn Java :)
You never added any toppings to your pizza,
Pizza newPizza = new Pizza(brand, size);
// Keep adding toppings, check for empty string to end?
while ((topping = getTopping()).length() > 0) {
newPizza.addTopping(topping); // <-- add the topping to the pizza.
}
System.out.println(newPizza.getPizzaInfo());
You also need to fix your method addTopping
public void addTopping(String topping) {
// toppings.add("topping");
toppings.add(topping);
}
As you specifically asked not to have us do your homework for you (which is good :) ) I will only give you the clues and pseudocode for what you need to do:
Right now you are just creating the Pizza object in PizzaMaker, but you are not doing anything with it. You have already created the methods to retrieve the toppings in PizzaMaker, the method getTopping(). You also have the method to add the toppings to the pizza in Pizza which is addTopping(). Now you just need to call the methods from PizzaMaker so they will be used.
The psuedocode should be like this:
Create the pizza object
For the number of toppings you want to add call getTopping()
For each topping you get you need to add that topping to you Pizza object with your addTopping() method.
Once all the toppings have been added, you can print out your pizza object.
It looks like you want to be able to ask the user for multiple toppings. So as a first approximation, let's assume the topics are single word only, separated by commas (something easy to test using the Scanner you have set up). I recommend two changes to your source code:
First, change the ArrayList of toppings to be called toppingList
private ArrayList<String> toppingList = new ArrayList<String>();
Next, change the addToppings(String toppings) to break the tuple entered by the user into tokens (delimited by spaces):
public void addToppings(String toppings) {
// Let's assume the user enters all toppings as single words delimited
// / by space
StringTokenizer strtok = new StringTokenizer(toppings);
while (strtok.hasMoreTokens()) {
String topping = strtok.nextToken();
toppingList.add(topping);
}
}
Lastly, you will need to call the addToppings method from your main program:
public static void main(String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
newPizza.addToppings(topping);
System.out.println(newPizza.getPizzaInfo());
}
One final note: make sure to close your Scanner instances, or you will have a resource leak. It's okay for this simple program, but if it were long-running, you have memory leaks.
To beef up your program, you could try:
Use a different delimiter, allowing multiple words in your toppings (like "Canadian Bacon" - two words),
Modify the getTopping() method to ask for the toppings one-at-a-time until the user presses some special key ("q to quit" is always a good one).
Have fun!
First mistake is you are not calling the methods you have defined in Pizza Class.
You are simply passing by constructor and initilizing the class variable and displaying those variable, but you are not passing the tropping value by constructor.
These below methods you are not calling anywhere .
/*public void changeBrand(String brandName) {
brand = brandName;
}
public void changeSize(int pizzaSize) {
size = pizzaSize;
}*/
Just Use this below code:-
public static void main( String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
newPizza.addTopping(topping);
System.out.println(newPizza.getPizzaInfo());
}
Output :-
Enter a brand name:
Manoj
Enter a size:
20
Enter topping:
pizaset 1
You want a 20 inch pizza made by: Manoj with these toppings:[pizaset 1]
Hope it will help you.
Its working now, I have tested.

Categories