Adding user input to ArrayList using do-while loop - java

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;
}
}

Related

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");
}

Modify class to write exceptions to text file

I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

I can't figure out how to print Hire and Fire from Stack

import java.util.*;
import java.util.Stack;
class Person {
private String name;
private String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
hire.push(app.dequeue());
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException{
Scanner keyboard = new Scanner (System.in);
Manager user = new Manager();
boolean test = true;
while (test){
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\t2 Hire \n\t3 Fire \n\t4 Quit:");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1){
user.Apply();
}else if (action == 2){
user.hire();
}else if (action == 3){
user.fire();
} else if (action == 4){
System.exit(0);
}
else{
System.out.println("Please try again.");
}
}
}
}
I can't figure out how I can print out the name and ssn of the person I just hired or fired. I tried using peek, but it's not working. Basically, the whole program is about whether to accept and application, hire or fire. If I accept an application, it will prompt for the user to enter their name and ss, and if I press hire/fire it should print out the name and ss of that person.
Youre defining the queue wrong.
Its more like: Queue<Person> app = new LinkedList<Person>();
and you need a print method. Here's the Manager class. The print is called in the the Management Class, and if you define Manager user = new Manager(); you're surly going to be looked at funny.
Remove all the Throws. They are not defined and are not used....
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
class Manager
{
Scanner keyboard = new Scanner(System.in);
//private Stack<Person> app = new Stack<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
Queue<Person> app = new LinkedList<Person>();
public void Apply()
{
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
//app.enqueue(apply);
app.add(apply);
}
public void hire()
{
if (!app.isEmpty())
{
hire.push(app.remove());
}
else
{
System.out.println("Nobody to hire.");
}
}
public void fire()
{
if (!hire.isEmpty())
{
fire.push(hire.pop());
}
else
{
System.out.println("Nobody to fire");
}
}
public void dump()
{
while(!app.isEmpty())
{
Person p = app.remove();
System.out.println(p.getName()+" "+ p.getSS());
}
}
}

Struggling with objects, program does not work as expected(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())

Scanner Input not Reading Method Calling as a Parameter

First of All here's the Codes:
Product Information:
public class ProductInformation
{
public String code;
public String itemName;
public double price;
//Constructor
public ProductInformation()
{ itemName="-";
code="-";
price=0;}
//Setter
public void setItemName(String itemName)
{ this.itemName=itemName;}
public void setCode(String code)
{ this.code=code;}
public void setPrice(double price)
{ this.price=price;}
//Getter
public String getItemName()
{ return itemName;}
public double getPrice()
{ return price;}
public String getCode()
{ return code;}
//Products
public void getProduct(String code)
{ if(code == "A001"){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code == "A002"){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code == "A003"){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code == "A004"){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code == "A005"){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
}
import java.util.*;
Product Display:
public class ProductDisplay
{ public ProductInformation product;
public ProductDisplay()
{
System.out.println("\t\t\t\t RG COMPUTER SHOP");
System.out.println("\t\t\t\t Makati City");
System.out.println("\t\tP R O D U C T\tI N F O R M A T I O N");
System.out.println("-------------------------------------------------------");
System.out.println("\t\tCode\t\tDescription\t\tUnit Price");
System.out.println("-------------------------------------------------------");
product = new ProductInformation();
product.getProduct("A001");
display();
product = new ProductInformation();
product.getProduct("A002");
display();
product = new ProductInformation();
product.getProduct("A003");
display();
product = new ProductInformation();
product.getProduct("A004");
display();
product = new ProductInformation();
product.getProduct("A005");
display();
}
// Display Method
public void display()
{ System.out.println("\t\t" + product.getCode()
+ "\t\t" + product.getItemName()
+ "\t\t" + product.getPrice()); }
}
My Problem is here in PointOfSale
I tried to let the buyer decide by entering a Product Code
after entering the getProduct I get is always "A005" Even if I enter "A001" or something else. I think the product.getProduct(code) is not working out. Can someone help me fix this problem so i can continue scripting this
import java.util.*;
public class PointOfSale extends ProductDisplay
{
public PointOfSale()
{ System.out.print("\nPurchase Item(y/n)?");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
if("y".equalsIgnoreCase(line)){
OpenOrder();
}
}
//=============================================
public void OpenOrder() // New Order
{ ArrayList<String> ProductList = new ArrayList<String>();
ProductList.add("A001"); ProductList.add("A002");
ProductList.add("A003"); ProductList.add("A004");
ProductList.add("A005");
System.out.print("Select Product Code:");
Scanner sc = new Scanner(System.in);
String code = sc.next();
if(ProductList.contains(code))
{ product.getProduct(code);
display(); EnterQuantity(); }
else System.out.print("Product Code is Invalid\n"); System.exit(0);}
//==============================================
public void EnterQuantity() //Entering Quantity
{
try{
System.out.print("Enter Quantity:");
Scanner sc = new Scanner(System.in);
int quantity = sc.nextInt();
double amount = quantity * product.getPrice();
System.out.print("Amount: " + amount);}
catch (InputMismatchException nfe)
{System.out.print("\nInvalid Entry: Input must be a Number.\n"); System.exit(0);}
}
// Main Method
public static void main(String[] args)
{ new PointOfSale(); }
}
You are comparing strings for equality in your getProduct() method. Strings are objects, so you probably want to use the equals() method:
public void getProduct(String code)
{ if(code.equals("A001")){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code.equals("A002")){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code.equals("A003")){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code.equals("A004")){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code.equals("A005")){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
One major problem is that you're comparing Strings using == and you in general shouldn't do that as this compares if one object reference is the same as another and you don't care about this. Instead you care if the two String variables hold the same String representation, and for this use the equals() or equalsIgnoreCase() methods.

Categories