Struggling with objects, program does not work as expected(java) - java

So I have this cyclingmanager game, and I want to show a list of riders by names, and then I want to show their abilities when the user picks a rider. The program compiles and runs nicely, the problem is in my riders() method.It just does not print out c1, my first rider. Thanks in advance.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CyclingManager2 {
public static void main(String[] args) {
//menyvalgene
Menu m = new Menu();
m.choice();
}
}
class Menu {
Scanner in = new Scanner(System.in);
Cyclist cy = new Cyclist();
//choices
public void choice() {
int choice = -1;
while (choice != 0) {
System.out.println("Choose something: ");
System.out.println("-0 will exit the program" + "\n-Pressing 1 will open the database menu");
choice = in.nextInt();
switch(choice) {
case 0: choice = 0; break;
case 1: database(); break;
default: System.out.println("You have to choose either 0 or 1"); break;
}
}
}
public void database() {
System.out.println("Welcome to the database \nThese are the options:\n0 = Back to menu\n1: Riders");
int dbChoice = -1;
while (dbChoice != 0) {
System.out.println();
dbChoice = in.nextInt();
switch(dbChoice) {
case 0: dbChoice = 0; break;
case 1: cy.riders(); System.out.println("Press 0 for going back to the menu\nPress 1 for showing the riders");break;
default: System.out.println("Choose either 0 or 1"); break;
}
}
}
}
class Cyclist {
List<Cyclist> cyclists = new ArrayList<>();
private String name;
private int mountain;
private int timeTrial;
private int sprint;
private int age;
Cyclist c1 = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMountain(int mountain) {
this.mountain = mountain;
}
public int getMountain() {
return mountain;
}
public void setTimeTrial(int timeTrial) {
this.timeTrial = timeTrial;
}
public int getTimeTrial() {
return timeTrial;
}
public void setSprint(int sprint) {
this.sprint = sprint;
}
public int getSprint() {
return sprint;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(((Cyclist) cyclists).getName());
}
}
public void abilities() {
//Pardilla is created
c1 = new Cyclist();
c1.setName("Sergio Pardilla");
c1.setMountain(75);
c1.setTimeTrial(60);
c1.setSprint(60);
c1.setAge(30);
/*System.out.println(c1.getName() + "'s abilities:");
System.out.println("Mountain - " + c1.getMountain());
System.out.println("TimeTrial - " + c1.getTimeTrial());
System.out.println("Sprint - " + c1.getSprint());
System.out.println("Age - " +c1.getAge());
cyclists.add(c1); //adds Pardilla to cyclists arraylist*/
}
}

You have this for-loop:
for (int i = 0; i < cyclists.size(); i++) {
System.out.print(((Cyclist) cyclists).getName());
}
It is not going to work. You are casting the entire cyclists (an ArrayList) to one cyclist instance. You probably want to iterate over the contents of the ArrayList and get each Cyclist-object in the cyclists array. Try a foreach-loop:
for (Cyclist cyclist : cyclists) {
System.out.print(cyclist.getName());
}
or use a for loop with index based retrieval:
for (int i = 0; i < cyclists.size(); i++) {
cyclists.get(i).getName());
}

I think you want more something like:
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(cyclists.get(i).getName());
}
}
Another thing, is that I'm not sure you want List<Cyclist> cyclists = new ArrayList<>(); to be part of Cyclist class.

Two issues:
The part where you add your rider to the ArrayList is commented out.
The way you loop over your ArrayList is by no means correct. Try like this:
for (Cyclist cyclist : cyclists) {
System.out.println(cyclist.getName());
}

You should get Objects from List by calling it number: cyclists.get(i).getName())

Related

How to compare Strings ignoring cases in Java

Newbie here I am trying to compare the brand and display to an array of Strings. Seems to be working now but I don't know how to make the comparison case-insensitive. All the options I found so far is to compare a string to another string. There is any way I can make that comparison? Right now only accept the values as stated in the array of strings.
P.S. This was an existing homework that our instructor wanted us to build on it, hence why I am using the "isValid" methods for validation.
Thanks!
import com.entertainment.Television;
import java.util.Arrays;
import java.util.Scanner;
class TelevisionConsoleClient {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
welcomeMessage();
}
public static void welcomeMessage() {
//Welcome message to buyer
System.out.println("Welcome to Our Online Ordering System.");
System.out.println("Please answer the questions below to submit your order.");
String brand = brandChoice();
String display = displayChoice();
int size = sizeChoice();
System.out.println("Thank you. The television you ordered is: ");
television(brand, display, size);
//close scanner
scanner.close();
}
public static String brandChoice() {
String brandChoice = null;
boolean hasBrand = false;
while (!hasBrand) {
System.out.println("Please enter the desired brand " + Arrays.toString(Television.VALID_BRANDS) + ":");
brandChoice = scanner.nextLine();
if (Television.isValidBrand(brandChoice))
hasBrand = true;
else
System.out.println("Sorry " + brandChoice + " is not a valid brand");
}
return brandChoice;
}
private static String displayChoice() {
String displayChoice = null;
boolean hasDisplay = false;
while (!hasDisplay) {
System.out.println("Please enter the desired display type " + Arrays.toString(Television.VALID_DISPLAY) + ":");
displayChoice = scanner.nextLine();
if (Television.isValidDisplay(displayChoice))
hasDisplay = true;
else
System.out.println("Sorry " + displayChoice + " is not a valid display type");
}
return displayChoice;
}
private static int sizeChoice() {
Integer sizeChoice = null;
boolean hasSize = false;
while (!hasSize) {
System.out.println("Please enter the desired size " + Arrays.toString(Television.VALID_SIZES) + ":");
sizeChoice = Integer.parseInt(scanner.nextLine());
if (Television.isValidSize(sizeChoice))
hasSize = true;
else
System.out.println("Sorry " + sizeChoice + " is not a valid size");
}
return sizeChoice;
}
private static void television(String brand, String display, int size) {
System.out.println(new Television(brand, display, size));
}
}
package com.entertainment;
public class Television {
// CLASS OR STATIC VARIABLES - STORED IN THE SHARED AREA ASSOCIATED WITH A CLASS
public static final String[] VALID_BRANDS = {"Samsung", "LG", "Sony", "Toshiba"};
public static final String[] VALID_DISPLAY = {"LED", "OLED", "PLASMA", "LCD", "CRT"};
public static final int[] VALID_SIZES = {32, 40, 43, 50, 55, 60, 65, 70, 75, 80};
// FIELDS - AKA 'INSTANCE VARIABLES', 'ATTRIBUTES', 'PROPERTIES'
private String brand;
private String display;
private int size;
// CONSTRUCTORS
// No-arg constructor.
public Television() {
// possible additional "setup" or initialization code here
// want it to run for every instance created
}
// 3-arg constructor
public Television(String brand, String display, int size) {
this.brand = brand;
this.display = display;
this.size = size;
}
// ACCESSOR METHODS (getters/setters)
public String getBrand() {
return brand;
}
public String getDisplay() {
return display;
}
public int getSize() { return size; }
public static boolean isValidBrand(String brand) {
boolean isValid = false;
for (String currentBrand : VALID_BRANDS) {
if (currentBrand.equals(brand)) {
isValid = true;
break;
}
}
return isValid;
}
public static boolean isValidDisplay(String display) {
boolean isValid = false;
for (String currentDisplay : VALID_DISPLAY) {
if (currentDisplay.equals(display)) {
isValid = true;
break;
}
}
return isValid;
}
public static boolean isValidSize(int size) {
boolean isValid = false;
for (int currentSize : VALID_SIZES) {
if (currentSize == size) {
isValid = true;
break;
}
}
return isValid;
}
public String toString() {
return "Television: " + getBrand() + ", Display: " + getDisplay() + ", Size: " + getSize() + " inches.";
}
}
Change String.equals(Object) to String.equalsIgnoreCase(String). That is,
if (currentBrand.equals(brand))
if (currentDisplay.equals(display))
to
if (currentBrand.equalsIgnoreCase(brand))
if (currentDisplay.equalsIgnoreCase(display))

ArrayList Collections error: which part of my code is wrong?

I would be required to write an array list of Mobile, do some operations such as add, remove, update and display. However, when it comes to sorting objects in arraylist, I am a little bit confused.
I am talking and referring to https://beginnersbook.com/2017/08/comparator-interface-in-java/
In drive class
//Create an arraylist of Mobile
ArrayList<Mobile> themobile = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Mobile");
System.out.println("Please select a number in the following: ");
while (true) {
//A list of options
System.out.println("1. Diplay the next mobile.");
System.out.println("2. Display the previous mobile.");
System.out.println("3. Add a new mobile.");
System.out.println("4. Remove a new mobile");
System.out.println("5. Update a mobile.");
System.out.println("0. Exit");
//prompt user input
int choice = input.nextInt();
switch(choice) {
case 1:
//displayNext(themobile);
break;
case 2:
//displayPrevious(themobile);
break;
case 3:
addMobile(themobile);
break;
case 4:
removeMobile(themobile);
break;
case 5:
updateMobile(themobile);
break;
case 0:
System.out.println("Thank you for using a Mobile arraylist");
System.exit(0);
}
}
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
}
In mobile class
public class Mobile implements Comparable<Mobile> {
private String brandName;
private int modelNumber;
private int internalMemoryS;
private int noOfAvailCameras;
public Mobile() {
}
public Mobile(String brandName, int modelNumber, int internalMemoryS, int noOfAvailCameras) {
this.brandName = brandName;
this.modelNumber = modelNumber;
this.internalMemoryS = internalMemoryS;
this.noOfAvailCameras = noOfAvailCameras;
}
public String getBrandName() {
return this.brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public int getModelNumber() {
return this.modelNumber;
}
public void setModelNumber(int modelNumber) {
this.modelNumber = modelNumber;
}
public int getInternalMemoryS() {
return internalMemoryS;
}
public void setInternalMemoryS(int internalMemoryS) {
this.internalMemoryS = internalMemoryS;
}
public int getNoOfAvailCameras() {
return noOfAvailCameras;
}
public void setNoOfAvailCameras(int noOfAvailCameras) {
this.noOfAvailCameras = noOfAvailCameras;
}
public int compareTo(Mobile m) {
return this.brandName.compareTo(m.getBrandName());
}
public String toString() {
return "Brand name: " + brandName + "Model number: " + modelNumber + "Internal memory space: " + internalMemoryS + "No of available cameras: " + noOfAvailCameras;
}
}
Each method has its own class & import java.util.*;
public class MobileByMoNum implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getModelNumber() - m2.getModelNumber();
}
}
public class MobileByBrandName implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getBrandName().compareTo(m2.getBrandName());
}
}
public class MobileByInS implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getInternalMemoryS() - m2.getInternalMemoryS();
}
}
Outcome:
TestMobile.java:48: error: unreachable statement
Collections.sort(themobile, new MobileByBrandName());
^
1 error
Any help and clarification is much appreciated. Thank you
As this code
while (true) {
never exits, the code below this loop is unreachable
Maybe System.exit(0); should maybe only be breaking the while loop.
Note break in a switch will not break the while loop
The code after while loop is never reached. You need to write some logic to break out of the while loop. One easy way to fix this is:
int choice = -1;
while (choice != 0) {
choice = input.nextInt();
switch (choice) {
//...other cases
case 0:
System.out.println("Thank you for using a Mobile arraylist");
}
}
Collections.sort(...);
System.out.println(...);
Put these lines inside while loop
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
Also you can simplify the operation of comparison by using Comparator.comparing available from java 8 onwards. Like:
Comparator<Mobile> comparator = Comparator.comparing(new Function<Mobile,
#Override
public String apply(Mobile t) {
return t.getBrandName();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getModelNumber();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getInternalMemoryS();
}
});
Collections.sort(themobile, comparator);

Why is method printing when there is no code to print

Attempting to get this output at the 2nd last part:
/*****test finalistsToFile2 with sorted arraylist*****/
/**************check file testSorted.txt**************/
/****************************************************/
However, my actual output is:
/****************************************************/
/*****test finalistsToFile2 with sorted arraylist*****/
/**************check file testSorted.txt**************/
**ID: 85011, Final Mark: 69.2, Classification: UPPER_SECOND
Candidate is BORDERLINE
ID: 62138, Final Mark: 59.9, Classification: LOWER_SECOND
Candidate is BORDERLINE**
/****************************************************/
I've attempted debugging but still cannot find the root cause of the extra 4 lines of printing under 'check file testSorted.txt' (in bold). Any idea what I can do? I have a total of 3 classes used as shown below:
ProcessDegreeMark class
import java.util.*;
import java.io.*;
public class ProcessDegreeMark{
private ProcessDegreeMark() {}
public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
ArrayList<Finalist> finalists = new ArrayList<Finalist>();
String id;
double mark;
Scanner in = null;
try
{
in = new Scanner(new FileReader(s));
try
{
while(in.hasNextLine())
{
id =in.nextLine();
mark = Double.parseDouble(in.nextLine());
finalists.add(new Finalist(id,mark));
}
}
finally
{
in.close();
}
}
catch(IOException e)
{
System.out.println(s+" not found");
}
return finalists;
}
public static void displayFinalists(ArrayList<Finalist> finalists){
for (int i = 0; i < finalists.size(); i++)
{
System.out.println(finalists.get(i));
}
}
public static void findFinalistID(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getId().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with ID number "+s);
}
}
public static void findFinalistClass(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
sortedFinalists.addAll(a);
Collections.sort(sortedFinalists, new FinalistComparator());
return sortedFinalists;
}
public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
try
{
PrintStream out = new PrintStream(new FileOutputStream(s));
try
{
for(int i = 0; i < finalists.size(); i++)
{
out.println(finalists.get(i));
}
}
finally
{
out.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
searchFinalists.add(a.get(i));
finalistsToFile2(searchFinalists,"testSorted.txt");
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static void main(String[] args) throws Exception{
System.out.println("/****************************************************/");
System.out.println("/*******finalistsInList with invalid file name*******/");
System.out.println();
ArrayList<Finalist> testList = finalistsInList("file***.txt");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/********finalistsInList with valid file name********/");
System.out.println("/********display to check arraylist populated********/");
System.out.println();
ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
displayFinalists(finalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*testing findFinalistID with valid and invalid data*/");
System.out.println();
findFinalistID(finalists, "75021");
findFinalistID(finalists, "21050");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findFinalistClass with valid and invalid data*/");
System.out.println();
findFinalistClass(finalists, "FIRST");
findFinalistClass(finalists, "THIRD");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****run sortedFinalists then test with display*****/");
System.out.println();
ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
displayFinalists(sortedFinalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
System.out.println("/**************check file testSorted.txt**************/");
System.out.println();
finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
System.out.println();
findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
System.out.println();
System.out.println("/*********************THE END************************/");
}
}
Finalist class
public class Finalist{
private String id;
private double degreeMark;
private String degreeClass;
private boolean borderline;
public Finalist(String id, double degreeMark) {
this.id = id;
this.degreeMark = degreeMark;
borderline = calcBorderline();
degreeClass = assignDegreeClass();
}
private String assignDegreeClass(){//change method name
if (degreeMark<40) return "FAIL";
if (degreeMark<50) return "THIRD";
if (degreeMark<60) return "LOWER_SECOND";
if (degreeMark<70) return "UPPER_SECOND";
return "FIRST";
}
private boolean calcBorderline(){
double x;
if (degreeMark<40){
x = 40.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<50){
x = 50.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<60){
x = 60.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<70){
x = 70.0-degreeMark;
if (x < 1.0) return true;
}
return false;
}
public String getId(){
return id;
}
public double getDegreeMark(){
return degreeMark;
}
public String getdegreeClass(){
return degreeClass;
}
public boolean getborderline(){
return borderline;
}
public String toString() {
String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
if(calcBorderline()==true)
{
System.out.print(s);
System.out.println("Candidate is BORDERLINE");
}
else if(calcBorderline()==false)
{
return s;
}
return "";
}
}
FinalistComparator class
import java.util.Comparator;
//sort by degree mark, descending
class FinalistComparator implements Comparator<Finalist> {
#Override
public int compare(Finalist f1, Finalist f2) {
int degreeComparisonResult = Double.compare(f2.getDegreeMark(),f1.getDegreeMark());
return degreeComparisonResult;
}
}
The unexpected output is performed in Finalist.toString() because of out.println(finalists.get(i));. Since PrintStream.println(Object x) calls toString() of the provided Object.
Update: since you stated that you need the second line: Candidate is BORDERLINE just add it to the return value and don't directly print it on System.out else you will get unexpected outputs.
#Override
public String toString() {
String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
if(calcBorderline()) {
s += "Candidate is BORDERLINE" + System.lineSeparator();
}
return s;
}
Original answer:
So avoid the use of System.out.println() in toString(), i would recommand to keep it as simple as possible and put logic in another method.
For example:
public class Finalist{
/* all the other code */
#Override
public String toString() {
return "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass;
}
}
public class ProcessDegreeMark {
/** Writes all non BORDERLINE candidates in the file and outputs the skipped finalists to System.out */
public static void saveToFileWithoutBorderline(List<Finalist> list, File file) {
try (PrintStream out = new PrintStream(new FileOutputStream(file))){
for(Finalist finalist : list) {
if(finalist.calcBorderline()) {
System.out.println("Skip BORDERLINE candidate: "+finalist.toString());
} else {
out.println(finalist.toString());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I only provided a sample code to skip the borderline candidates in saveToFile, since I didn't know where you have to skip or suppress them.

Getting the output from a arraylist

Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}

Adding user input to ArrayList using do-while loop

I am trying to add user input to an Arraylist using a do-while loop however I keep ending up with a list consisting of only the final item inputed repeated several times.
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while(!response.equals("done"));
return toBuy;
}
should work as mentioned in my comment.
Please implement a toString() method in your Item class if not done already.
you should replace your System.out.println as following:
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
}
} while(!response.equals("done"));
for (Item item : toBuy){
System.out.println(item);
}
return toBuy;
}
if this doesn't helps, please share some more code.
Here is fully working example
package stackoverflow;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Q53837506 {
public static void main(String[] args) {
ArrayList<Item> purchaseItems = purchaseItems();
System.out.println(purchaseItems);
}
public static class Item {
String r;
int v;
public Item(String r, int v) {
super();
this.r = r;
this.v = v;
}
#Override
public String toString() {
return "Item [r=" + r + ", v=" + v + "]";
}
}
static final Random randGen = new Random();
public static ArrayList<Item> purchaseItems() {
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
Scanner in = new Scanner(System.in);
do {
response = in.nextLine();
if (!response.equals("done")) {
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while (!response.equals("done"));
return toBuy;
}
}

Categories