creating a shopping catalog in netbeans - java

Create a java file in NetBeans, name it Catalog.java.
Create one String array to store 3 products for a catalogue
Create the appropriate variables to store the product name, product code and product price.
At the start of the program display the catalogue for the user by looping through the array and outputting it to the screen with a number listing for each product, as shown above
Create an infinite loop to enter orders; to stop the loop the user should enter 0.
Keep a running total (accumulator) of all products amount total and sub-total (multiple accumulators)
Write a method to calculate the taxes and return a grand total
Write another method to print out the order as listed above
its supposed to be entered like this
I would like to know how to have the user input like this and be stored in an array.
Enter Order Number (0 to stop): M3487
Enter Quantity: 2
Enter Order Number (0 to stop): W3876
Enter Quantity: 3
Enter Order Number (0 to stop): R9983
Enter Quantity: 3
Enter Order Number (0 to stop): 0
when i enter the code "M3487" its not going to the quantity, its ending the program.
This is the code I have so far. I'm a beginner, so please bear with me.
package catalog;
import java.util.*;
public class Catalog {
static String products[] = new String[3];
static int answer;
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Shopping Catalog");
System.out.println("------------------");
String[] pCode = new String[3];
float pPrice[] = new float[3];
int orderNum = 0;
int quantity=0;
Scanner s = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("condensed milk [M3487], $9.50 per can.");
System.out.println("");
System.out.println("Distilled Water [W3876], $3.00 a bottle.");
System.out.println("");
System.out.println("Pack Rice [R9983], $12.75 for 5lbs.");
System.out.println("------------------------------------------");
do{
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
orderNum++;
if(pCode[orderNum] == ("M3487")){
System.out.println("condensed milk $9.50");
System.out.println("Enter Quantity");
quantity = s.nextInt();
}//close if statement
if(answer == 0){
break;
}//close if
}while(true);//close while loop
}//close main method
}//close class

System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
orderNum++; //This is the problem
if(pCode[orderNum] == ("M3487"))//It will not work because you have change the index
Remove
orderNum++;
because You have inserted string at pCode[0] zero index and searching at pCode[1].
Change you code to:
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
if(pCode[orderNum].equals("M3487")){
System.out.println("condensed milk $9.50");
System.out.println("Enter Quantity");
quantity = s.nextInt();
}
orderNum++;

Related

How to store the data on every instance of do-while loop in Java?

I am currently studying Java and I need to add the values of every instance in my do-while loop. Is there some way to store the values so it won't be overwritten every loop?
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
int itemQty = input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
You can define a variable for the totalSum outside of the loop and then everytime the user enters a number, add itemQty to it.
int totalSum = 0;
do {
...
int itemQty = input.nextInt();
totalSum += itemQty;
...
} while (...);
// Here totalSum is the sum of all user inputs
you can update your program like this below -
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char userChar;
int itemQty = 0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty += input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
totalQty+=itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
As suggested by Lino, Keep itemQty outside the loop and initialize it to zero.
Do you also want to store the value of itemQty for every loop iteration?
If yes then use ArrayList.
ArrayList<int> valuesList = new ArrayList<int>();
and change your loop code to
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
valuesList.add(itemQty*10);//New line to be added
totalQty += itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
And then after the loop ends, display the values in each stage.
for (int i = 0; i < valuesList.size(); i++) {
System.out.println("The value of Qty in stage "+(i+1)+" is $"+valuesList.get(i));
}
And this will be your final output
Apples are $10
How many do you want?
10
Do you wish to buy more? (y/n)
y
Apples are $10
How many do you want?
5
Do you wish to buy more? (y/n)
n
The total is: $150
The value of Qty in stage 1 is $100
The value of Qty in stage 2 is $50

Scanner won't allow me to continue after fixing an invalid response

So I've written a test class to test a program that will allow me to take in number of courses, letter grades, and course credits and then calculate total weighted points, total credits, and GPA within a loop designed for 3 courses max.
However, I need to validate the number of courses and prove that it will run after both an invalid and valid input have been entered.
I've gotten it so that will prompt the user for a valid number of courses after an invalid response, but once the valid response is input the program just stops instead of running like it is supposed to. Can anyone tell me why?
Here's my code:
import java.util.*;
import java.lang.*;
public class ComputeGpa
{
public static void main(String [] args)
{
Gpa grades1 = new Gpa();
Scanner in = new Scanner (System.in);
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
if(courses > 0)
{
int i = 0;
while(i < 3)
{
System.out.println("Please enter a letter grade.");
String letter = in.next();
char result = letter.charAt(0);
System.out.println("How many credits was this class worth?");
int credits = in.nextInt();
grades1.addToTotals(result, credits);
i++;
}
System.out.printf("GPA: %.2f", grades1.calcGpa());
}
else
{
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
}
}
The output for that is as follows:
Enter number of courses:
-2
Number of courses must be greater than 0. Please enter a valid number of courses.
3
And then the program stops running. Where Am I going wrong? I thought the in.next() on the letter String would fix this problem but apparently I was wrong. Any ideas?
Your flow is currently if/else.
int foo = ...;
if(foo > 0) {
//your grade stuff
}
else {
//ask for reinput
}
What ends up happening is you catch the problem input once, but never give your flow the opportunity to check it again.
Instead, use a while loop over an if/else layout, to force re-entry until you get the exact information you want, then continue.
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
while(courses < 0) {
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
int i = 0;
//...

Find the length of an arraylist when the arraylist is located in a different Class

So I'm trying to find out the length of an arraylist, but the arraylist is being stored in a different class, how am I able to fix this.
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
public class StarberksInterface
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
store = new Store();
String str, sName1, sName2, name;
char c;
int n=0;
sName1 = "Callahan";
sName2 = "Lambton";
//This is the main menu that will be displayed first.
System.out.println(" MAIN MENU FOR MANAGEMENT SYSTEM");
System.out.println("===============================================");
System.out.println("1. CHOOSE STORE");
System.out.println("2. DISPLAY STORES");
System.out.println("3. LOAD STORE VIA FILE");
System.out.println("4. SAVE STORE TO FILE ");
System.out.println("5. EXIT PROGRAM");
System.out.println("===============================================");
while(n!=5)// Exits the program when 4 is pressed
{
System.out.print("\n Please enter option 1-4 to continue...: ");
n = Integer.parseInt(System.console().readLine());
// Reads user input and takes them to selected code.
if (n>5||n<1)
{
System.out.print("Invalid input, please try again...");
continue;
}
if (n==1)// Takes to option 1 or sub menu
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
System.out.println("Enter a store name [Callahan or Lambton] ");
name = console.next();
if (sName1.equals(name)|| sName2.equals(name))
{
StarberksInterface.subMenu();
continue;
}
else
{
System.out.println("There is no store under this name. Please try again.");
}
}
}
if (n==2)// Gathers products in stores and displays the number of products
{
System.out.println(" Store data is being displayed.");
System.out.println("===============================");
System.out.println("Store: Callahan");
System.out.println(" Number of products: "+store.size());
}
}
}
so that code above is for where I want the length to be displayed.
this code is where the arraylist is populated.
public static Product product;
public static Store store;
// Where the user inputs the data for the item
public static void addItem ()
{
Scanner console = new Scanner(System.in);
product = new Product();// initiates the product and store to being empty.
String desc, id, str="";
double price = 0, sUpPrice = 0, unitCost = 0, inventoryCost = 0;
int stock = 0, demand = 0;
System.out.print("Please enter product description between 3 to 10 characters...: ");
desc = console.next();
desc = desc.toLowerCase();
product.setName(desc);
if ((desc.length() < 3 || desc.length() > 10))
{
System.out.println("\nThis Input is incorrect. Please make description between 3 to 10 characters.\n");
System.out.println("Try again with different input. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.print("Please enter price in $ : ");
price = console.nextDouble();
product.setPrice(price);
if (price < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.print("Please enter set up price. $ : ");
sUpPrice = console.nextDouble();
product.setsUpPrice(sUpPrice);
if (sUpPrice < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.print("Please enter unit- cost. $ : ");
unitCost = console.nextDouble();
product.setunitCost(unitCost);
if (unitCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.print("Please enter the inventory cost. $ : ");
inventoryCost = console.nextDouble();
product.setinvCost(inventoryCost);
if (inventoryCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.print("Please enter the amount in stock : ");
stock = console.nextInt();
product.setstock(stock);
if (stock < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.print("Please enter the demand of the product : ");
demand = console.nextInt();
product.setdRate(demand);
if (demand < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
StarberksInterface.addItem();
}
System.out.println("\n*****************************************\n");
System.out.print(desc +" Product was added successfully ");
System.out.println("\n*****************************************\n");
// stores the item in the array
//Checks to see if item is already in the list
/*while (product != null)
{
if (product.equals(store.getProduct(desc)))
{
System.out.println(desc +" is already a product.");
System.out.println("Input for data will restart");
StarberksInterface.addItem();
}
}*/
store.add(product);
}
and finally the following code is in a file called Store.java, this is where the arraylist is.
import java.util.ArrayList;
public class Store{
// stores the product information in an array list
//allows for numerous products and each can be called in the Starberks Interface
public ArrayList <Product> ProductList = new ArrayList<Product> ();
public Store()
{
}
public void add(Product product)
{
// Adds the product and all details entered by user to the list.
ProductList.add(product);
}
public Product getProduct(String prodName) {
//
for (int i = 0; i < ProductList.size(); i++) {
//searches through list of products to find a specific name entered in
// from the Starberks Interface
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
}
It's not another file, it's another class. To access a member of a class, you need to access it via an object of that class. For example, in your code, you can access the arraylist by using new Store().ProductList. Although this would be empty at first, but after you added some products into it, this would have some objects.
As you are using store.size(), I think you need a method size() declared in your Store class, which would return the size of your arraylist.
By the way, there are some general issues in your code
1. Public variables/objects in class
2. getProduct() is returning null, which is hiding it's true purpose.
You need to define a getter method inside your Store class to access the size of list
/*your list reference has a size() method that you can call to get the size of list in store class and can access that via a getter */
public int getProductListSize(){
return ProductList.size();
}
Also in your any other class where you have store class reference you can access it easily like
store. getProductListSize();

How do you get your program to repeat if input is invalid instead of continuing with invalid input?

I am trying to validate a user input, cuPerTerm > 12
I get the error message but the program continues and uses the invalid input to run
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
int cuToComp;
int cuPerTerm;
public static void main(String[] args) {
final double COST = 2890.00; //flat-rate tuition rate charged per term
final int MONPERTERM = 6; //number of months per term
int cuToCompTotal = 0;
int numTerm;
int numMonToComp;
double tuition;
//prompt for user to input the number of CUs for each individual course remaining.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
//add all CUs from individual courses to find the Total number of CUs left to complete.
while (cuToComp > 0)
{
cuToCompTotal += cuToComp;
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
cuToComp = in.nextInt();
}
System.out.println("The total number of CUs left is " + cuToCompTotal);
//prompt for user to input how many CUs they plan to take per term.
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm <12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
{
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
}
//Calculate the number of terms remaining, if a remain is present increase number of terms by 1.
numTerm = cuToCompTotal/cuPerTerm;
if (cuToCompTotal%cuPerTerm > 0)
{
numTerm = numTerm + 1;
}
System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");
//Calculate the number of Months left to complete
numMonToComp = numTerm * MONPERTERM;
System.out.println("Which is " + numMonToComp + " Months. ");
//calculate the tuition cost based on the number of terms left to complete.
tuition = numTerm * COST;
System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
}
}
I need it to continue to re-ask until 12 or something greater is entered. and then continue the program.
You should use a while loop so that you continue looping until cuPerTerm is at least 12. Remember to take the user input again with cuPerTerm = in.nextInt(); inside the while loop.
Here's a simple solution:
int cuPerTerm = -1; // intialize to an invalid value
while (cuPerTerm < 12) {
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm <12) { //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
}
}
Add this to continue getting input till it satisfies your condition:
while(cuPerTerm <= 12){
//Ask use to provide input
}
It is simple while loop which checks your input condition and continues taking input till it is satisfied.
Edit: -
Initialize your cuPerTerm =0
while(cuPerTerm <= 12)
{
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
}
There are pitfalls: Simple doing scanner.nextInt() will give you the next Integer of the CURRENT Line.
If the user types in test, nextInt() will throw an InputMismatchException, you have to handle. Also the int will NOT be consumed
So you have to call scanner.nextLine() in between to Clean the current (mismatched) result.
All together something like this:
do{
try
{
System.out.print("Enter number > 12: ");
System.out.flush();
number = scanner.nextInt();
if (number > 12)
done = true;
}
catch(InputMismatchException e) {
System.out.println("This is not a number");
scanner.nextLine() //!Important!
}
}while(!done);
I think that a do-while loop will best suit your needs:
int val;
do {
val = in.nextInt();
} while (val < 12);

inputs and loops

I'm trying to do as the picture shows here:
This is my code:
import java.util.Scanner;
public class IcsProject
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner (System.in);
int menuNum,ID,semNum,semCode,semCourses;
do{
System.out.println("Please Enter your Choice from the menu:");
System.out.println("1. Enter Student Sanscript");
System.out.println("2. Display Transcript Summary");
System.out.println("3. Read Student Franscript from a File");
System.out.println("4. Write Transcript Summary to a File");
System.out.println("5. Exit");
menuNum = keyboard.nextInt();
if (menuNum == 2 || menuNum == 3 || menuNum == 4)
System.out.println("Not working");
} while (menuNum > 1 && menuNum < 5);
//// Option 1: Enter student transcript
if (menuNum == 1)
System.out.println("Please enter your student's FIRST and LAST name:");
String stuName = keyboard.nextLine();
System.out.println("Please enter the ID number for " + stuName);
ID = keyboard.nextInt();
System.out.println("Please enter the number of semesters");
semNum = keyboard.nextInt();
for(int i=1 ; i < semNum ; i++)
{System.out.println("Please enter semester code for semester n# " + semNum);
semCode = keyboard.nextInt();
System.out.println("Please enter the number of courses taken in " + semCode );
semCourses = keyboard.nextInt();}
System.out.println("Enter course code, credit hours, and letter grade ")
///I stopped here
}
Do I have to use array starting from the semester code? show me an example please.
After entering all the values The program should show the Menu again so I can choose from it. How to do that?
I'm having a problem at the first question "entering the student first and last name"
The program just skip it and move to next question. Is there a mistake with my keyboard.nextLine();
I would use a list of objects which have all the fields you want to record.
For examples, just use google.
http://www.google.com/search?q=java+list+examples 27.9 million result
http://www.google.com/search?q=java+object+examples 18 million results.
http://www.google.com/search?q=java+array+examples 15 million results.
Regarding issue #2 - put the menu in a separate method. use a loop that it's condition is the menu or something similar to process according to the result from menu (this is abstract, I think you can figure it out from here):
while(doAnotherLoop)
{
switch(showMenu())
{
case 1:
...
case 2:
...
case 5: // Exit
doAnotherLoop = false;
}
}
Regarding issue #3. You read an int: menuNum = keyboard.nextInt(); but the line is not over, so the next nextLine (String stuName = keyboard.nextLine();) takes the rest of the line. use nextLine() and parse the integers instead.

Categories

Resources