ArrayList elements aren't printed - java

I'm pretty new to java and what i'm trying to do is make a model for a catalog storing available products in a computer parts shop, using collections. My instructor asked for one instance of each product in the catalog. This is what i came up with:
import java.util.*;
public class AvailablesCatalog {
public AvailablesCatalog(List cat1) {
cat1 = new ArrayList();
Motherboard item1 = new Motherboard("MD4652", 1995, "Lenovo", 100.50, "Intel", 32, 5);
CPU item2 = new CPU("MD4652", 1995, "Lenovo", 100.50, 2.9, 6);
Graphics item3 = new Graphics("MD4652", 1995, "Lenovo", 100.50, "AMD", 6);
RAM item4 = new RAM("MD4652", 1995, "Lenovo", 100.50, "DDR2", 4, 1600);
HD item5 = new HD("MD4652", 1995, "Lenovo", 100.50, "SSD", 2.5, 750);
Monitor item6 = new Monitor("MD4652", 1995, "Lenovo", 100.50, "LED", 17.5, "1920x1080", "HDMI");
Keyboard item7 = new Keyboard("MD4652", 1995, "Lenovo", 100.50, "Wireless");
Mouse item8 = new Mouse("MD4652", 1995, "Lenovo", 100.50, "Laser", "Wireless");
Printer item9 = new Printer("MD4652", 1995, "Lenovo", 100.50, "Laser", "Colored");
cat1.add(item1);
cat1.add(item2);
cat1.add(item3);
cat1.add(item4);
cat1.add(item5);
cat1.add(item6);
cat1.add(item7);
cat1.add(item8);
cat1.add(item9);
}
public String toString(List cat1, int i) {
for(i=0; i<cat1.size(); i++) {
System.out.println(cat1.get(i).toString());
}
return "----------------------------------------------------";
}
}
Now, through the shop's mainApp that i'm using to to print the catalog, i have stored an instance of the AvailablesCatalog object type in a variable called av. This is the mainApp:
public class mainApp {
public static void main(String[] args){
/* Variables for Menu System and Sub Menu System */
int MainMenu;
String SubMenu;
String ReturnToMenu;
String SubMenuReturnToMenu;
List cat1 = new ArrayList();
AvailablesCatalog av = new AvailablesCatalog(cat1);
/* Displays menu system to console */
System.out.println("..............MENU...............");
System.out.println("..............1 View All Available Products..............");
System.out.println("..............2 View Orders...................");
System.out.println("..............3 View Sales...................");
System.out.println("..............0 Exit...................");
System.out.print("Please select an option: ");
Scanner sc = new Scanner(System.in);
MainMenu = sc.nextInt();
if(MainMenu == 1){
for(int i = 0; i < cat1.size(); i++) {
System.out.println(av.toString(cat1, i));
}
}
else if(MainMenu == 2) {
System.out.println("lol");
}
else if(MainMenu == 3) {
System.out.println("lol3");
}
else if(MainMenu == 4) {
System.exit(0);
}
}
}
Everything compiles smoothly, and when i run mainApp the menu shows up correctly. But when i press 1 to print the available products catalog, the programm simply ends. Options 2 and 3 are simply placeholders for now btw. Thanks in advance.

You are using two different Lists in your program.
The first one is cat1in your main method (is empty)
The second in your constructor (is filled in the constructor)
You override the reference with the new created list in the constructor and fill that one instead. This is garbage collected after the constructor is finished and no reference is pointing on it.
In the toString method you are printing the the list that is passed via parameter which is the one from main (and empty).
Remove the cat1 = new ArrayList(); line from the constructor. Then it should work.

Related

Unable to call required method from relevant class

I have a task where I need to create a program for "TotalCompetitions", which consists of multiple "Competition". I need to create an application which allows user to do various options related to TotalCompetition.
If the first option ("Create a new competition") is selected, by typing "1" and then pressing Enter,
the program should call the addNewCompetition method of the TotalCompetitions class to add
a new competition with a given name. After creating a new competition, the program should goes
back to the main menu.
The second option is to add entries to the competition. However, when I try to call the addEntry() method located in the Competition class to the newly created competition, it doesn't work as it is still of TotalCompetitions type. How can I access the newly created competition to access the required method?
At the moment, this is my code:
public class TotalCompetitions {
private ArrayList<Competition> competitions;
public TotalCompetitions() {
this.competitions = new ArrayList<Competition>();
}
public ArrayList<Competition> getCompetitions() {
return competitions;
}
public void setCompetitions(ArrayList<Competition> competitions) {
this.competitions = competitions;
}
public Competition addNewCompetition(String name, int id) {
Competition newCompetition = new Competition(name, id);
return newCompetition;
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
TotalCompetitions sc = new TotalCompetitions();
int competitionId = 0;
while (true) {
System.out.println("Please select an option. Type 5 to exit.");
System.out.println("1. Create a new competition");
System.out.println("2. Add new entries");
System.out.println("3. Draw winners");
System.out.println("4. Get a summary report");
System.out.println("5. Exit");
String command = keyboard.next();
if (command.equals("1")) {
keyboard.nextLine();
System.out.println("Competition name:");
String name = keyboard.nextLine();
competitionId += 1;
sc.addNewCompetition(name, competitionId);
System.out.println("A new competition has been created!");
System.out.println("Competition ID: " + competitionId + ", Competition Name: " + name);
}
else if (command.equals("2")) {
sc.addEntry();
}
else if (command.equals("5")) {
System.out.println("The end");
break;
}
}
sc.addNewCompetition(name, competitionId); returns a new object of the type Competition, however, this new object is not used by your program. The variable sc is still of the type TotalCompetition which is not related to the type Competition. Furthermore, your method addNewCompetition(String id, int id) does not add the new Object to the ArrayList. The solution would be to store the object which is returned by the sc.addNewCompetition(...) call and call addEntry() on this object.

Want to print full Array.asList , Only printing one line

I am developing an Application in Android Studio to that prints how many of each item you can buy with the given amount of currency. It printed flawlessly when run as a Java program in Eclipse but I can not get it to print more than one line in the TextView Box.
I've noticed it will pick the most Expensive item you can afford 1 of and print it alone, leading me to believe it runs through the list and only prints the last one that passes as affordable. I've read about needing to use a StringBuilder and such but have found little information on how to convert my Array.asList over to this. Here is my code.
gCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText diamondInput = (EditText) findViewById(R.id.diamondInput);
try {
int diamonds = Integer.parseInt(diamondInput.getText().toString());
List<Gifts> gift = Arrays.asList(new Gifts[]{new Gifts("Gold star", 10), new Gifts("Love Bear", 10), new Gifts("Lillies", 10), new Gifts("Box Of Chocolate", 20), new Gifts("Taco", 20), new Gifts("Thumbs Up", 30), new Gifts("Panda", 40), new Gifts("Beer", 40), new Gifts("Patriot", 52), new Gifts("Eagle", 52), new Gifts("Gold Chain", 80), new Gifts("Roses", 100), new Gifts("Champagne", 100), new Gifts("Snow", 100), new Gifts("Candy", 100), new Gifts("Kiss", 200), new Gifts("Candy Hearts", 250), new Gifts("Peach", 300), new Gifts("EggPlant", 300), new Gifts("Fireworks", 500), new Gifts("GemDrop", 600), new Gifts("Crown", 600), new Gifts("Cupcakes", 700), new Gifts("Heart Balloon", 800), new Gifts("Sports Car", 1000), new Gifts("Smoke Rings", 1000), new Gifts("purple Diamond", 2500), new Gifts("Cupid", 5000), new Gifts("Gold Watch", 5000), new Gifts("Castle", 5000), new Gifts("Yacht", 10000), new Gifts("Jet", 20000)});
double coins = (double) diamonds / 2.5D;
Iterator var5 = gift.iterator();
while(var5.hasNext()) {
Gifts Gifts = (Gifts)var5.next();
int qty = (int)Gifts.getQty(coins);
if(qty > 0) {
result.setText("You can buy " + qty + " " + Gifts.name);
}
}
}
catch (Exception e) {
// friendly error to the user: field is incorrect
}
I need it to print as this EX:
You can buy X amount of Y
You can buy X amount of Y
You can buy X amount of Y
:end
Printing every item that can be bought and it's quantity.
If you look into Android API documentation (https://developer.android.com/reference/android/widget/TextView.html) , this is what it states:
void setText (CharSequence text) - sets the text to be displayed. - this means that each time you call this method, new text overrides the old one.
It seems that you are looking for append() method:
void append(CharSequence text) - convenience method to append the specified text to the TextView's display buffer, upgrading it to EDITABLE if it was not already editable. append() method doesn't override previously set text.
Another way to append text to the previously stored in TextView is to combine these methods:
result.setText(result.getText() + "text that you want to append to the previous one")

java swing: Query list of Jcombobox<String>

I am just beginning with Java and Java swing.
I am working on a small meal plan program to check that the user eats all types of proteins.
It has a Jcombobox for 2 meals a day.
Is there a way to query all boxes using a for loop?
I tried this but it's not liking it:
public LunchMenu() {
initComponents();
Hashtable<String, Integer> Proteins = new Hashtable<>();
Proteins.put("Beef", 0);
Proteins.put("Chicken", 0);
Proteins.put("Fish", 0);
Proteins.put("Pork", 0);
Proteins.put("None", 0);
}
/**
*
*/
public void runCheck() {
String[] comboBoxes = new String[14];
comboBoxes = {"MonLun", "MonDin", "TueLun", "TueDin", "WesLun", "WesDin", "ThuLun", "ThuDin", "FriLun", "FriDin", "SatLun", "SatDin", "SunLun", "SunDin"};
for (String str : comboBoxes) {
String temp;
temp = (String)str.getSelectedItem();
lunch.Lunch.Proteins[temp]++;
}
}

Advance to next card object with different elements while using java's cardlayout

I am very new to this site and a novice programmer so I'm hoping someone here can help me with the problem I'm facing. I am making a simple program that uses a card layout to select/enter several user-specific options that will be stored in string variables and then after the last question, used to give a unique answer. Right now the program advances slide's successfully and displays the proper question, however it does not clear the JRadioButton from the first card and keeps using this radio button instead of the desired component for the duration of the program. For example, The second and third card should have JTextField's while the 4th card should have a JComboBox. I have two main class files, one that is the actual frame and the other that is displayed below which does the work behind the scenes. For future reference, I plan to modify this into an applet once it is working properly so any advice on that would be great. Any help will be greatly appreciated, thanks.
I believe the problem may stem from the creation of multiple card objects here, the ScreenPanel objects each take the same parameters but depending on the different card, a different Component needs to be produced.
// set up questions
String question1 = "Sex: ";
String[] responses1 = {"Female", "Male"};
ask[0] = new ScreenPanel(question1, responses1);
String question2 = "Height in inches: ";
String[] responses2 = new String[1];
ask[1] = new ScreenPanel(question2, responses2);
String question3 = "Weight in pounds: ";
String[] responses3 = new String[1];
ask[2] = new ScreenPanel(question3, responses3);
String question4 = "Event: ";
String[] responses4 = {"Shot Put", "Discus Throw", "Long Jump", "Triple Jump", "High Jump", "Pole Vault", "4 x 800 Relay", "100 Meter Hurdles", "100 Meter Dash", "4 x 200 Relay",
"1600 Meter Run", "4 x 100 Relay", "400 Meter Dash", "300 Meter Hurdles", "800 Meter Run", "200 Meter Dash", "3200 Meter Run", "4 x 400 Relay"};
ask[3] = new ScreenPanel(question4, responses4);
String question5 = "Distance(inches) or Time(seconds)";
ask[4] = new ScreenPanel(question5, new String[1]);
ask[4].setFinalQuestion(true);
addListeners();
}
The Screen Panel class here creates each card, could be a problem with the conditionals but not sure.
class ScreenPanel extends JPanel{
JLabel question;
JRadioButton[] response1;
JTextField response2;
JTextField response3;
JComboBox response4;
JTextField response5;
JButton nextButton = new JButton("Next");
JButton finalButton = new JButton("Finish");
String textResponse1, textResponse2, textResponse3, textResponse4, textResponse5;
ScreenPanel(String ques, String[] resp){
super();
setSize(320, 260);
question = new JLabel(ques);
JPanel sub1 = new JPanel();
JPanel sub2 = new JPanel();
sub1.add(question);
if (TrackAndField.currentScreen == 0){
response1 = new JRadioButton[resp.length];
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < resp.length; i++){
response1[i] = new JRadioButton(resp[i], false);
group.add(response1[i]);
sub2.add(response1[i]);
}
// textResponse1 = group.getSelection().toString();
}
if (TrackAndField.currentScreen == 1){
sub2.remove(response1[0]);
sub2.remove(response1[1]);
response2 = new JTextField(4);
KeyAdapter monitor = new KeyAdapter() {
public void keyTyped(KeyEvent event){
textResponse2 = response2.getText();
}
};
sub2.add(response2);
}
if (TrackAndField.currentScreen == 2){
sub2.remove(response2);
response3 = new JTextField(10);
KeyAdapter monitor = new KeyAdapter() {
public void keyTyped(KeyEvent event){
textResponse3 = response3.getText();
}
};
sub2.add(response3);
}
if (TrackAndField.currentScreen == 3){
sub2.remove(response3);
response4 = new JComboBox(resp);
sub2.add(response4);
textResponse4 = response4.getSelectedItem().toString();
}
Solved by adding an extra string parameter as an ID for the component and used that for the conditionals instead of currentScreen

How would i go about adding to my array through JOptionpanes?

At the moment I have to manually add items to my array but I would like to enable users to do this themselves perhaps through JOptionPanes, what would be the best way to go about this? Here is my current code.
public class Main {
public static void main(String[] args){
//Create new Person objects
Address p[] = new Address[3];
p[0] = new Address("27","Abbey View","Hexham","NE46 1EQ");
p[1] = new Address("15", "Chirdon Crescent", "Hexham", "NE46 1LE");
p[2] = new Address("6", "Causey Brae", "Hexham", "NE46 1DB");
Details c[] = new Details[3];
c[0] = new Details ("3", "175,000", "Terraced");
c[1] = new Details ("6", "300,000", "Bungalow");
c[2] = new Details ("4", "250,000", "Detached");
//Send some messages to the objects
c[0].setBeds("3 ");
c[1].setBeds("6");
c[2].setBeds("4");
c[0].setPrice("175,000");
c[1].setPrice("300,000");
c[2].setPrice("250,000");
c[0].setType("Terraced");
c[1].setType("Bungalow");
c[2].setType("Detached");
//Set up the association
p[0].ownsDetails(c[0]);
p[1].ownsDetails(c[1]);
p[2].ownsDetails(c[2]);
//print details
p[1].printDetails();
p[2].printDetails();
p[3].printDetails();
}
System.exit(0);
}
}
You could use the showXXXX methods on JOptionPane and keep prompting the user just as you would on the console.
However, I suggest just creating a simple JFrame that would have controls that allows the user to enter multiple items instead of showing one dialog after another.

Categories

Resources