I've tried many different ways to fix the error. I know it has something to do with the hasNext, I'm just not sure where the error is. Please help. Also if someone could tell me how I can get the value of the variable largestQuantity into the main method from my getLargestQuantityItem method I'd appreciate that. Cheers!
Here is the input file that is a .txt file:
The Shawshank Redemption
100
19.95
DVD
The Dark Knight
50
19.95
DVD
Casablanca
137
9.95
DVD
The Girl With The Dragon Tattoo
150
14.95
Book
Vertigo
55
9.95
DVD
A Game of Thrones
100
8.95
Book
Here is my code:
import java.util.*;
import java.io.*;
public class Project01 {
public static void main(String[] args) {
ArrayList<String> Titles = new ArrayList<String>();
ArrayList<String> Types = new ArrayList<String>();
ArrayList<Double> Prices = new ArrayList<Double>();
ArrayList<Integer> Quantities = new ArrayList<Integer>();
int count = 0;
Scanner in = new Scanner(System.in);
String database = getFile(in);
try {
File file = new File(database);
Scanner inputFile = new Scanner(file);
System.out.println();
System.out.println("Product Summary Report");
System.out.println("------------------------------------------------------------");
while (inputFile.hasNext()) {
getTitle(Titles, inputFile.nextLine());
getQuantity(Quantities, inputFile.nextInt());
getPrice(Prices, inputFile.nextDouble());
getType(Types, inputFile.next());
System.out.println("Title: " + Titles.get(count));
System.out.println(" Product Type: " + Types.get(count));
System.out.println(" Price: " + Prices.get(count));
System.out.println(" Quantity: " + Quantities.get(count));
System.out.println();
count++;
inputFile.next();
}
System.out.println("-----------------------------------------------------------------");
System.out.println("Total products in database: " + count);
System.out.println("Largest quantity item: " + largestQuantity);
System.out.println("Highest total dollar item: ");
System.out.println("Smallest quantity item: ");
System.out.println("Lowest total dollar item: ");
System.out.println("-----------------------------------------------------------------");
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + database);
}
in.close();
}
private static String getFile(Scanner inScanner) {
System.out.print("Enter database filename: ");
String fileName = inScanner.nextLine();
return fileName;
}
private static void getTitle(ArrayList<String> Titles, String title) {
Titles.add(title);
}
private static void getType(ArrayList<String> Types, String type) {
Types.add(type);
}
private static void getPrice(ArrayList<Double> Prices, double price) {
Prices.add(price);
}
private static void getQuantity(ArrayList<Integer> Quantities, int quantity) {
Quantities.add(quantity);
}
private static void getLargestQuantityItem(ArrayList<Integer> Quantities){
Integer largestQuantity = Collections.max(Quantities);
}
}
Here is the output and the error I'm receiving:
Enter database filename:
Product Summary Report
------------------------------------------------------------
Title: The Shawshank Redemption
Product Type: DVD
Price: 19.95
Quantity: 100
Title: Dark Knight
Product Type: DVD
Price: 19.95
Quantity: 50
Title:
Product Type: DVD
Price: 9.95
Quantity: 137
Title: Girl With The Dragon Tattoo
Product Type: Book
Price: 14.95
Quantity: 150
Title:
Product Type: DVD
Price: 9.95
Quantity: 55
Title: Game of Thrones
Product Type: Book
Price: 8.95
Quantity: 100
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at Project01.main(Project01.java:31)
In reference to this post and your txt file.
Add inputFile.nextLine() after your nextInt(), nextDouble() method.
getQuantity(Quantities, inputFile.nextInt());
inputFile.nextLine();
getPrice(Prices, inputFile.nextDouble());
inputFile.nextLine();
Change below code
getType(Types, inputFile.nextLine());
And remove your inputFile.next(); at the end of your while loop.
Second approach will be just add if block around your next(); method call.
if (inputFile.hasNext()) {
inputFile.next();
}
The problem was that next(); at the end of the while loop was reading the next element. But at the end of file after Book there was nothing to read so it was throwing Exception at that line.
Update:
largestQuantity is a local variable, it can not be accessed outside the method. You should return it from getLargestQuantityItem method. So change the return type of your method and then return the max value.
private static Integer getLargestQuantityItem(ArrayList<Integer> Quantities){
return Collections.max(Quantities);
}
And in main method
To get Largest quantity item:
System.out.println("Lowest total dollar item: ");
Integer largestQuantityMainVariable = getLargestQuantityItem(Quantities);
System.out.println("Largest quantity : " + largestQuantityMainVariable);
int index;
for (int i = 0; i < Quantities.size(); i++) {
if (Quantities.get(i) != null && Quantities.get(i).equals(largestQuantityMainVariable)) {
index = i;
break;
}
}
System.out.println("Largest quantity item : " + Titles.get(index));
Update 2:
For the question in the comments The only thing I have left is to find the highest and lowest total dollar value. I need to somehow take the quantity times the price and then look for the max and min value out of those values
private static List<Double> generateTotalPriceList(List<Double> prices, List<Integer> quantities) {
List<Double> totalPriceList = null;
if (prices != null && prices.size() > 0
&& quantities != null && quantities.size() > 0) {
if (prices.size() == quantities.size()) {
totalPriceList = new ArrayList<Double>();
double totalValue;
for (int i = 0; i < prices.size(); i++) {
totalValue = prices.get(i) * (double) quantities.get(i);
totalPriceList.add(totalValue);
}
}
}
return totalPriceList;
}
In main method
List<Double> totalPriceList = generateTotalPriceList(Prices, Quantities);
Now you can follow the procedure as we did for Quantity.
Related
To begin my question, here is my question prompt:
Create a program using classes that does the following in the zyLabs developer below. For this lab, you will be working with two different class files. To switch files, look for where it says "Current File" at the top of the developer window. Click the current file name, then select the file you need.
(1) Create two files to submit:
ItemToPurchase.java - Class definition
ShoppingCartPrinter.java - Contains main() method
Build the ItemToPurchase class with the following specifications:
Private fields
String itemName - Initialized in default constructor to "none"
int itemPrice - Initialized in default constructor to 0
int itemQuantity - Initialized in default constructor to 0
Default constructor
Public member methods (mutators & accessors)
setName() & getName() (2 pts)
setPrice() & getPrice() (2 pts)
setQuantity() & getQuantity() (2 pts)
(2) In main(), prompt the user for two items and create two objects of the ItemToPurchase class. Before prompting for the second item, call scnr.nextLine(); to allow the user to input a new string. (2 pts)
Ex:
Item 1
Enter the item name: Chocolate Chips
Enter the item price: 3
Enter the item quantity: 1
Item 2
Enter the item name: Bottled Water
Enter the item price: 1
Enter the item quantity: 10
(3) Add the costs of the two items together and output the total cost. (2 pts)
Ex:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13
My code:
ItemToPurhase.java
public class ItemToPurchase {
//Private fields - itemName, itemPrice, and itemQuanity
private String itemName = "none";
private int itemPrice = 0;
private int itemQuantity = 0;
/*Default Constructor
itemName - Initialized to "none"
itemPrice - Initialized to 0
itemQuantity - Initialized ito 0
*/
public ItemToPurchase () {
this.itemName = "none";
this.itemPrice = 0;
this.itemQuantity = 0;
}
//public member methods (mutators & accessors)
//setName() & getName()
public void setName (String itemName) {
this.itemName = itemName;
}
public String getName() {
return itemName;
}
//setPrice() & getPrice()
public void setPrice (int itemPrice) {
this.itemPrice = itemPrice;
}
public int getPrice(){
return itemPrice;
}
//setQuantity() & getQuantity()
public void setQuantity (int itemQuantity) {
this.itemQuantity = itemQuantity;
}
public int getQuantity() {
return itemQuantity;
}
//print item to purchase
public void printItemPurchase() {
System.out.println(itemQuantity + " " + itemName + " $" + itemPrice +
" = $" + (itemPrice * itemQuantity));
}
}
ShoppingCartPrinter.java
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 0;
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
// Get item 1 details from user, create itemToPurchase object
System.out.println("Item 1");
System.out.println("Enter the item name: ");
productName = scnr.next();
item1.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item1.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item1.setQuantity(productQuantity);
System.out.println("");
// Get item 2 details from user, create itemToPurchase object
System.out.println("Item 2");
System.out.println("Enter the item name: ");
productName = scnr.next();
item2.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item2.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item2.setQuantity(productQuantity);
System.out.println("");
// Add costs of two items and print total
cartTotal = (item1.getQuantity() * item1.getPrice()) + (item2.getQuantity() * item2.getPrice());
System.out.println("TOTAL COST");
// cartTotal = item one price + item two price
// Totoal Cost
// item one information
int item1Total = item1.getPrice() * item1.getQuantity();
System.out.println(item1.getName() + " " + item1.getQuantity() + " # $" + item1.getPrice() + " = $" + item1Total);
// item two information
int item2Total = item2.getPrice() * item2.getQuantity();
System.out.println(item2.getName() + " " + item2.getQuantity() + " # $" + item2.getPrice() + " = $" + item2Total);
// Total output
System.out.println("");
System.out.print("Total: $" + cartTotal);
return;
}
}
Although I am getting no errors for most of the submissions, there are 2 submissions that raise the "Exception in thread "main" java.util.InputMismatchException" error.
Example:
Exited with return code 1.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ShoppingCartPrinter.main(ShoppingCartPrinter.java:23)
Output differs. See highlights below.
Input:
Chocolate Chips
3
1
Bottled Water
1
10
Your output:
Item 1
Enter the item name:
Enter the item price:
Expected output(!):
Item 1
Enter the item name:
Enter the item price:
Enter the item quantity:
Item 2
Enter the item name:
Enter the item price:
Enter the item quantity:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13
My code seems correct for other inputs that are very similar but for some reason, the compiler that my professor uses keeps prompting this error for a very few cases.
If you have not already done so, I suggest that you read the documentation for class java.util.Scanner.
This line of your code is throwing the InputMismatchException.
productPrice = scnr.nextInt();
That means that scnr read a token that was not an int. This is because your product contained two words, namely Chocolate Chips. So this line of your code only read Chocolate
productName = scnr.next();
and hence method nextInt read Chips which is not an int.
You need to change the code and call method nextLine rather than method next. Again, refer to the documentation to understand why.
Also, after calling method nextInt and before calling method nextLine, you need an extra call to method nextLine. Refer to Scanner is skipping nextLine() after using next() or nextFoo()? to understand why.
Only class ShoppingCartPrinter needs to be changed. Here is the changed code. I have added comments to indicate the changes, namely CHANGE HERE and ADDED THIS LINE.
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 0;
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
// Get item 1 details from user, create itemToPurchase object
System.out.println("Item 1");
System.out.println("Enter the item name: ");
productName = scnr.nextLine(); // CHANGE HERE
item1.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item1.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item1.setQuantity(productQuantity);
scnr.nextLine(); // ADDED THIS LINE
System.out.println("");
// Get item 2 details from user, create itemToPurchase object
System.out.println("Item 2");
System.out.println("Enter the item name: ");
productName = scnr.nextLine(); // CHANGE HERE
item2.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item2.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item2.setQuantity(productQuantity);
System.out.println("");
// Add costs of two items and print total
cartTotal = (item1.getQuantity() * item1.getPrice())
+ (item2.getQuantity() * item2.getPrice());
System.out.println("TOTAL COST");
// cartTotal = item one price + item two price
// Totoal Cost
// item one information
int item1Total = item1.getPrice() * item1.getQuantity();
System.out.println(item1.getName() + " " + item1.getQuantity() + " # $" + item1.getPrice()
+ " = $" + item1Total);
// item two information
int item2Total = item2.getPrice() * item2.getQuantity();
System.out.println(item2.getName() + " " + item2.getQuantity() + " # $" + item2.getPrice()
+ " = $" + item2Total);
// Total output
System.out.println("");
System.out.print("Total: $" + cartTotal);
return;
}
}
In a project for school, I'm required to make a menu system with the following options:
Load employees’ data - prompts user for the number of employees to be loaded and then prompts for each employee name, id (5 digit number), and annual salary
Add new employee - prompts user for an employee data, name, id, and annual salary
Display all employees - displays each employee’s data to the console, one employee per line
Retrieve specific employee’s data - prompts user for the employee id and displays the corresponding employee’s data: id, name, and salary
Retrieve employees with salaries based on range - prompts user for the lowest and highest salary and displays all employees with salaries in that range. Display each employee on separate line with all information - name, id, and salary
Exit
Each menu choice must be it's own be its own method, and he prefers we use arrays instead of lists, which is why I allotted 100 spaces. Here is what I have so far. Menu options 1, 2, and 6 run without breaking the program. But anything where things have to be displayed seems to break. My best guess is that there is an issue with passing and updating the array "employees" between all of the methods.
package practice;
import java.util.Arrays;
import java.util.Scanner;
public class Project {
public static Employee[] loadData() {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("How many employees would you like to add?"); //Determines how many employees to create
Employee[] employees = new Employee[100];
int numberEmployees = scanint.nextInt();
for (int i = 0; i < numberEmployees; i++) {
System.out.println("Enter name: ");
String empName = scanstr.nextLine();
System.out.println("Enter ID: ");
int empID = scanint.nextInt();
System.out.println("Enter Salary: ");
int empSalary = scanint.nextInt();
employees[i+1] = new Employee(empName, empID, empSalary); //Add employee to array
}
return employees;
}
public static Employee addEmployee() {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("Enter name: ");
String empName = scanstr.nextLine();
System.out.println("Enter ID: ");
int empID = scanint.nextInt();
System.out.println("Enter salary: ");
int empSalary = scanint.nextInt();
return new Employee(empName, empID, empSalary);
}
public static void displayEmployees(Employee[] employees) {
for (int i = 0; i < employees.length; i++) {
if (employees[i] != null) {
System.out.println(Arrays.toString(employees));
//System.out.println("Employee Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
}
}
public static void specificEmployee(Employee[] employees, int id) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].id == id) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("ID not recognized");
}
}
}
public static void salaryRange(Employee[] employees, int salaryMinimum, int salaryMaximum) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].salary >= salaryMinimum && employees[i].salary <= salaryMaximum) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("No employees within salary range");
}
}
}
public static void main(String[] args) {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
int menuChoice = 0;
while (menuChoice != 6) {
System.out.println("\tMenu:");
System.out.println("1. Load Employee Data");
System.out.println("2. Add New Employee");
System.out.println("3. Display All Employees");
System.out.println("4. Retrieve Specific Employee Data");
System.out.println("5. Retrieve Employees Within Salary Range");
System.out.println("6. Exit");
menuChoice = scanint.nextInt();
Employee[] employees = new Employee[100];
int amountEmployees;
if (menuChoice == 1) {
employees = loadData();
}
else if (menuChoice == 2) {
employees[0] = addEmployee();
}
else if (menuChoice == 3) {
displayEmployees(employees);
}
else if (menuChoice == 4) {
System.out.println("Enter 5 digit employee ID: ");
int id = scanint.nextInt();
specificEmployee(employees, id);
}
else if (menuChoice == 5) {
System.out.println("Enter minimum of salary range: ");
int salaryMinimum = scanint.nextInt();
System.out.println("Enter maximum of salary range");
int salaryMaximum = scanint.nextInt();
salaryRange(employees, salaryMinimum, salaryMaximum);
}
else if (menuChoice == 6) {
break;
}
else {
System.out.println("Invalid Choice");
}
}
scanint.close();
scanstr.close();
}
Any help would be appreciated!!!!!
There are a few problems in your code:
while (menuChoice != 6) {
System.out.println("\tMenu:");
System.out.println("1. Load Employee Data");
System.out.println("2. Add New Employee");
System.out.println("3. Display All Employees");
System.out.println("4. Retrieve Specific Employee Data");
System.out.println("5. Retrieve Employees Within Salary Range");
System.out.println("6. Exit");
menuChoice = scanint.nextInt();
**Employee[] employees = new Employee[100];**
int amountEmployees;
if (menuChoice == 1) {
employees = loadData();
}
You have declared the employees array inside the while loop, so each time you read an input you are creating a new one. This totally defeats the purpose of storing employees in an array and later retrieving them, which also makes the assignment redundant if menuChoice == 1. You must think about where you should declare your array.
public static void specificEmployee(Employee[] employees, int id) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].id == id) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("ID not recognized");
}
}
}
When you declare an array, the values by default are null, unless you assign them some values. Here, you are iterating the entire array and checking for employee id. You should consider what would happen if the employee at a particular index in the array is null. You must have checks for such cases.
A similar problem is in one of the other methods that you have created. I will let you debug that on your own.
And as suggested by #NomadMaker - Your second menu item only sets element 0 of the array. You can't add two or more employees.
I would suggest, you try to dry run your code and if you find it tough, try debugging it in an ide.
For my program, I need to display the item description, quantity, and price in a chart-like format. So that means that description of item 1 would be in line with its price and quantity. So far, I've tried several methods I found on the Internet but haven't succeeded. I am using Dr. Java so please suggest something that is compatible with that compiler.
Thank you in advance!
Here's what I have so far:
public static void main(String []args){
Scanner input=new Scanner(System.in);
String sentinel = "End";
String description[] = new String[100];
int quantity[] = new int[100];
double price [] = new double[100];
int i = 0;
// do loop to get input from user until user enters sentinel to terminate data entry
do
{
System.out.println("Enter the Product Description or " + sentinel + " to stop");
description[i] = input.next();
// If user input is not the sentinal then get the quantity and price and increase the index
if (!(description[i].equalsIgnoreCase(sentinel))) {
System.out.println("Enter the Quantity");
quantity[i] = input.nextInt();
System.out.println("Enter the Product Price ");
price[i] = input.nextDouble();
}
i++;
} while (!(description[i-1].equalsIgnoreCase(sentinel)));
// companyArt();
//System.out.print(invoiceDate());
//System.out.println(randNum());
System.out.println("Item Description: ");
System.out.println("-------------------");
for(int a = 0; a <description.length; a++){
if(description[a]!=null){
System.out.println(description[a]);
}
}
System.out.println("-------------------\n");
System.out.println("Quantity:");
System.out.println("-------------------");
for(int b = 0; b <quantity.length; b++){
if(quantity[b]!=0){
System.out.println(quantity[b]);
}
}
System.out.println("-------------------\n");
System.out.println("Price:");
System.out.println("-------------------");
for(int c = 0; c <price.length; c++){
if(price[c]!=0){
System.out.println("$"+price[c]);
}
}
System.out.println("-------------------");
//This is where I multiply the price and quantity together to get the total
double total = 0.0;
for (int j = 0; j < quantity.length; j++){
total += quantity[j] * price[j];
}
if(total != 0){
System.out.println("Total: " + total);
}
}
}
Your code prints out a list of item descriptions, followed by a list of quantities, followed by a list of prices. I'm assuming this is not how you want it to look. The best solution would be to use a single for loop that prints each of these three things out per line. The following code prints out a table with three columns labelled "Item Description", "Quantity", and "Price", with each row representing an item, and dashed lines separating each row:
System.out.println("Item Description:\tQuantity:\tPrice:\t");
System.out.println("---------------------------------------------------------");
for(int a = 0; a <description.length; a++){
if (description[a].equalsIgnoreCase("end")) {
break;
}
System.out.println(description[a] + "\t\t" + quantity[a] + "\t\t" + price[a]);
System.out.println("---------------------------------------------------------\n");
}
The output will be formatted like this:
Item Description: Quantity: Price:
---------------------------------------------------------
asdfaoiew;rjlkf 248 4309.0
---------------------------------------------------------
asodifaasd 43 2323.0
---------------------------------------------------------
asdfasoif 234 2.0
---------------------------------------------------------
If the columns don't line up properly, you'll need to either add or remove one "\t" after the description, depending on how long or short your item descriptions are.
Is there any other coding or code format for this kind of output? I would like to ask for your help again. Thank you in advance! This is about array. I tried this using vector but I don't really get the idea. Please really need help.
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Looks like you are either adding products or displaying them.
Instead of maintaing 4 different ArrayLists, use a class Product and maintain 1 list.
class Product {
Integer prodNum;
String prodName;
Integer prodPay;
Integer prodPrice;
}
List<Product> listOfProducts = new ArrayList<Product>();
Also the 4 if blocks for 'code' can be replaced by a switch statement.
I'm trying to use the items of one array within a for loop that is looping through another array. For example, I want to display the item name (an array that already exists) when asking for the price of each of these items. "What price is item[i]". I don't think you can use item[i] in this instance. I've also tried using a get method and using a counter variable, but I must be doing something wrong.
The readPrice portion isn't working - specifically the item[i]. Does anyone have a suggestion how to accomplish the same thing without using item[i]?
I'm new to java, so I'm sorry if this is an obvious answer, but I would really appreciate the help!
Here is my code:
private String[] items;
private int[] priority;
private double[] price;
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("You will need to enter seven shopping items.");
items = new String[7];
for (int i = 0; i < items.length; i++)
{
System.out.println("Enter an item: ");
items[i] = keyboard.nextLine();
}
}
**public void readPrice()**
{
price = new double[7];
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i < price.length; i++)
{
System.out.println("Enter the price for " + **items[i]**);
price[i] = keyboard.nextDouble();
}
}
you can make a class Item.
public class Item {
String name;
double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return "Item{" + "name=" + name + ", price=" + price + '}';
}
}
After create an object of class Item
public class TestPaper {
public static void main(String[] args) {
Item item;
Item[] itemTable = new Item[7];
ArrayList<Item> itemlist = new ArrayList<>();
for (int i = 0; i < 7; i++) {
item = new Item();
//set value
item.setName("item1");
item.setPrice(200);
//store the object to a table or an arraylist
itemTable[i] = item;
itemlist.add(item);
}
for (Item temp : itemTable) {
System.out.println(temp.toString());
}
}
}
This is better solution, but I will answer you with your code.
You have 7 items, so you can print the items like this:
private String[] items;
private int[] priority;
private double[] price;
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("You will need to enter seven shopping items.");
items = new String[7];
for (int i = 0; i < items.length; i++)
{
System.out.println("Enter an item: ");
items[i] = keyboard.nextLine();
}
}
**public void readPrice()**
{
price = new double[7];
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i < price.length; i++)
{
System.out.println("Enter the price for " + **items[i]**);
price[i] = keyboard.nextDouble();
}
public void printdata(){
for(int I=0; I<7; I++){
System.out.println("item name: " +item[i] +" price: "+price[i])
}
}
Alright, well here's the answer for you. There are two main approaches to this: either pass the object items as a parameter, or make it global.
Global Variable Approach
For the global approach, which you seem to sort of already be doing, first declare your object as a field for your class:
class MyClass
{
private String[] items = new String[7];
//...Rest of class goes here
}
Now you can access it from your two methods as you wish.
public readInput()
{
// Add stuff to items
items[0] = "hi";
}
public readPrice()
{
// Read from items
System.out.println(items[0]);
}
Method Parameter Approach
Now if you want to actually pass an object from one method to another but don't want it to be accessible to any other methods, you can make it a parameter like this:
public readPrice(String[] items)
{
// Read from items
System.out.println(items[0]);
}
And then you can call the method from somewhere else passing specific instances of the object type.
public inputPrice()
{
String[] items = new String[7];
// Add stuff to items
items[0] = "hi";
this.readPrice(items);
}
Passing parameters is especially useful if you want to call a single method several times, but have it act on different inputs.
Please provide a stacktrace of the occurring error to make everyone happy. I personally would create a Map to assign a price to an item.
Code
package test;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Items {
private int itemsLength = 10;
private Map<String, Double> items = new HashMap<>();
public Items() {
System.out.println("Please fill in the details below: ");
for(int i = 0; i < itemsLength; i++) {
Scanner in = new Scanner(System.in);
String itemName;
Double price;
System.out.println("Enter an item name: ");
itemName = in.nextLine();
System.out.println(String.format("Enter %s's price: ", itemName));
price = in.nextDouble();
items.put(itemName, price);
}
System.out.println("Here are your items: ");
System.out.println("+------------------------+");
System.out.println(String.format("|%-10s | %-10s %-6s", "Item", "Price", "|"));
for (Entry<String, Double> entry : items.entrySet()) {
System.out.println(String.format("|%-10s | %-10s %-6s", entry.getKey(), entry.getValue(), "|"));
}
System.out.println("+------------------------+");
}
}
Output
Please fill in the details below:
Enter an item name:
Shoes
Enter Shoes's price:
20
Enter an item name:
Shirt
Enter Shirt's price:
20
Enter an item name:
Necklace
Enter Necklace's price:
50
Enter an item name:
Bracelet
Enter Bracelet's price:
30
Enter an item name:
Socks
Enter Socks's price:
5
Enter an item name:
Flip-flops
Enter Flip-flops's price:
10
Enter an item name:
Soda
Enter Soda's price:
2
Enter an item name:
Diamonds
Enter Diamonds's price:
20000
Enter an item name:
Weird Item
Enter Weird Item's price:
99999
Enter an item name:
Another Weird Item
Enter Another Weird Item's price:
99999
Here are your items:
+------------------------+
|Item | Price |
|Necklace | 50.0 |
|Another Weird Item | 99999.0 |
|Shirt | 20.0 |
|Bracelet | 30.0 |
|Diamonds | 20000.0 |
|Weird Item | 99999.0 |
|Shoes | 20.0 |
|Socks | 5.0 |
|Soda | 2.0 |
|Flip-flops | 10.0 |
+------------------------+
P.S: This is my first response, sorry if its not pretty
Edit: If you want to keep the order when outputting then construct a TreeMap instead of a HashMap.