How can i use Empty String to terminate? - java

I just want to follow this condition, but the problem is that when i enter the empty, it will be continue loop infinity.
Please Enter either S (supply) or R (replenish) followed by ID and quantity.
R p122 10
New Stock-level for p125 (Pedal) is 18
S p905 20
No part found with ID p905
Empty String (to terminate)
Display the final.
I also try the following code, but it couldn't work
if (n.equals("")){
code
}
Here's my code:
import java.util.*;
public class TestPart {
public static void main(String[] args)
{
Part[] part = new Part[5];
part[0] = new Part("p122", "Chain", 48, 12.5 );
part[1] = new Part("p123", "Chain Guard", 73, 22.0 );
part[2] = new Part("p124", "Crank", 400, 11.5 );
part[3] = new Part("p125", "Pedal", 38, 6.5 );
part[4] = new Part("p126", "Handlebar", 123, 9.50 );
Scanner src = new Scanner(System.in);
String n;
String id;
int qty;
System.out.print("Please Enter either S(supply) or R(replenish) followed by ID and quantity:\n");
int a = 0;
do
{
n = src.next();
id= src.next();
qty= src.nextInt();
boolean found = false;
for(int i = 0; i< part.length; i++)
{
if(part[i].getID().equals(id))
{
found = true;
String name = part[i].getName();
int stockLevel = part[i].getStockLevel();
if(id.equals(part[i].getID()) && n.charAt(0) == 'S')
{
double amount = part[i].supply(qty);
if(amount>0){
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is " + part[i].getStockLevel());
}
else{
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is not available" );
}
}
else if (id.equals(part[i].getID()) && n.charAt(0) == 'R')
{
part[i].replenish(qty);
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is " + part[i].getStockLevel());
}
}
}
if (found == false)
{
System.out.println("No part found with ID " + id );
}
System.out.println("");
for(int i=0; i<part.length; i++)
{
System.out.println(part[i].getID()+ "\t"+part[i].getName()+"\t"+part[i].getStockLevel()+"\t"+part[i].getUnitPrice() );
}
}while(a ==0);
}

If you want to terminate when the input line is empty
do{
String line = src.nextLine();
String [] inputs = null;
if(!line.matches("\\s*")){
String n ;
String id ;
int qty;
inputs = line.split(" ");
if(inputs.length ==3)
{
n = inputs[0];
id = inputs[1];
qty = (int) Integer.parseInt(inputs[2]);
}
else if(inputs.length ==2)
{
id = inputs[0];
qty = (int) Integer.parseInt(inputs[1]);
}
// Your Logic
}
else
break;
}while(a==0)

Your code is:
a = 0;
do {
// ...
}while(a ==0);
that's why it loop infinitively.

Related

while and for loop to infinite in java

i have a exercice to do in Java. I need to create a World Cup tournament and the restriction is that the program will restart until my favourite team win. However, if my team didn't win after 20 times, the program stop
The problem is when I try to put the second restriction (20 times max) with a for after the while (true), I always get an infinite loop.
//Q1
String[] teams16 = {"Uruguay", "Portugal", "France", "Argentina", "Brazil", "Mexico",
"Belgium", "Japan", "Spain", "Russia", "Croatia", "Denmark", "Sweden", "Switzerland",
"Colombia", "England"};
//data
Scanner keyboard = new Scanner(System.in);
Random result = new Random();
System.out.print("Enter your favourite team: ");
String team = keyboard.nextLine();
boolean teamwc = false;
// choice of the favourite team
for (int i = 0 ; i < 16 ; i++ ) {
if (teams16[i].equalsIgnoreCase(team)) {
teamwc = true;
}
}
if(teamwc == false) {
System.out.println("Your team is not in the Round of 16 ");
}
// the tournament begins (ROUND OF 16)
while (true) {
if (teamwc == true) {
int z = 0;
String[] winnerof16 = new String[8];
int a = 0;
System.out.print("ROUND OF 16:");
for (int i = 0; i < 16 ; i+=2) {
int score1 = result.nextInt(5);
int score2 = result.nextInt(5);
if (score1 > score2) {
winnerof16 [a] = teams16[i];
}
else if (score1 < score2) {
winnerof16[a] = teams16[i+1];
} else if (score1 == score2) {
Random overtime = new Random();
int ot = overtime.nextInt(2);
if (ot == 0) {
score1++;
winnerof16[a] = teams16[i];
} else if (ot == 1) {
score2++;
winnerof16[a]=teams16[i+1];
}
}
System.out.print("["+teams16[i] +"]"+ " " + score1+":"+score2 + " " + "["+teams16[i+1]+"]" + " ");
a++;
}
System.out.println();
String[] winnerof8 = new String[4];
int b = 0;
System.out.print("QUARTER-FINALS:");
for (int k = 0 ; k < 8 ; k+=2) {
int score3 = result.nextInt(5);
int score4 = result.nextInt(5);
if (score3 > score4) {
winnerof8[b]=winnerof16[k];
}
else if (score3 < score4) {
winnerof8[b] = winnerof16[k+1];
} else if (score3 == score4) {
Random overtime2 = new Random();
int ot2 = overtime2.nextInt(2);
if (ot2 == 0) {
score3++;
winnerof8[b]=winnerof16[k];
} else if (ot2 == 1) {
score4++;
winnerof8[b]=winnerof16[k+1];
}
}
System.out.print("["+winnerof16[k] +"]"+ " " + score3+":"+score4 + " " + "["+winnerof16[k+1]+"]" + " ");
b++;
}
System.out.println();
String[] winnerof4 = new String[2];
int c = 0;
System.out.print("SEMI-FINALS:");
for (int l = 0 ; l < 4 ; l+=2) {
int score5 = result.nextInt(5);
int score6 = result.nextInt(5);
if (score5 > score6) {
winnerof4[c]=winnerof8[l];
}
else if (score5 < score6) {
winnerof4[c] = winnerof8[l+1];
} else if (score5 == score6) {
Random overtime3 = new Random();
int ot3 = overtime3.nextInt(2);
if (ot3 == 0) {
score5++;
winnerof4[c]=winnerof8[l];
} else if (ot3 == 1) {
score6++;
winnerof4[c]=winnerof8[l+1];
}
}
System.out.print("["+winnerof8[l] +"]"+ " " + score5+":"+score6 + " " + "["+winnerof8[l+1]+"]" + " ");
c++;
}
System.out.println();
String[] winnerof2 = new String[1];
int d = 0;
System.out.print("FINALS:");
for (int m = 0 ; m < 2 ; m+=2) {
int score7 = result.nextInt(5);
int score8 = result.nextInt(5);
if (score7 > score8) {
winnerof2[d]=winnerof4[m];
}
else if (score7 < score8) {
winnerof2[d] = winnerof4[m+1];
} else if (score7 == score8) {
Random overtime4 = new Random();
int ot4 = overtime4.nextInt(2);
if (ot4 == 0) {
score7++;
winnerof2[d]=winnerof4[m];
} else if (ot4 == 1) {
score8++;
winnerof2[d]=winnerof4[m+1];
}
}
System.out.print("["+winnerof4[m] +"]"+ " " + score7+":"+score8 + " " + "["+winnerof4[m+1]+"]" + " ");
System.out.println();
}
System.out.println("Tournament: " + z + " The WINNER is: " + winnerof2[d]);
z++;
if (winnerof2[d].equalsIgnoreCase(team)) {
break;
}
}
}
}
}
This is my code before I put the second restriction.
Is there a problem with my code ? How can I put the second restriction ? Thank you
The infinite loop is due to this 2:
while (true) { // it will quit while loop only when an exception raised
if (teamwc == true) { // after this you nowhere assign teamwc == false therefore it is always true
instead of direct assigning True to while loop, use a boolean variable or a condition to quit somewhere:
t = true
while(t):
OR
while n>0:

Why can't my binary search find the passwords I am generating for my array of strings?

import java.util.*;
import java.io.*;
public class A3 {
public static void main(String args[])
{
Accept inputScanner = new Accept();
Assign3 sortObj = new Assign3();
String lname[] = {"","","","",""};
String psw[] = {"","","","",""};
String input;
do
{
System.out.println("Password Generator");
System.out.println("Please enter 5 last names:");
for (int index = 0; index < lname.length; index++)
{
System.out.print("Please enter last name: ");
lname[index] = inputScanner.acceptInputString();
psw[index] = sortObj.generatePassword(lname, index);
}
sortObj.sortArrayDescending(lname);
sortObj.arrayDisplay(lname, psw);
Screen.scrollscreen(70, 1, '=');
System.out.print("Please enter name to search (e or E to exit):");
input = inputScanner.acceptInputString();
int password = sortObj.binSrch(lname, input);
if(password >= 0)
{
System.out.println("Name: " + input + " ===> " + "password: " + password);
System.out.println("++++++++++++++++++++++++++++++++++");
}
else
{
System.out.println(input + " is not found");
System.out.println("++++++++++++++++++++++++++++++++++");
}
}while(input.equals("e") && input.equals("E"));
}
public void sortArrayDescending(String[] lnameArray)
{ String temp;
for(int j = 1; j < lnameArray.length - 1; j++)
{
for(int index = 0; index < lnameArray.length - 1; index++)
{
if(lnameArray[index].trim().compareTo(lnameArray[index+1].trim())<0)
{
temp = lnameArray[index];
lnameArray[index] = lnameArray[index + 1];
lnameArray[index + 1] = temp;
}
}
}
}
public void arrayDisplay(String lnameContent[], String pswContent[])
{
for(int i = 0; i < lnameContent.length; i ++)
{
System.out.println(lnameContent[i] + " " + pswContent[i]);
}
}
public int binSrch(String strArr[], String search)
{
int mid = -1;
int first = 0;
int last = strArr.length - 1;
boolean found = false;
while(first <= last)
{
mid = (first + last) / 2;
if(strArr[mid].equalsIgnoreCase(search))
{
found = true;
break;
}
else if(strArr[mid].compareToIgnoreCase(search) < 0)
{
last = mid - 1; //use lower half
}
else
{
first = mid + 1; //use upper half
}
}
if(!found)
{
mid = -1;
}
return mid;
}
public String generatePassword(String[] str, int index)
{
String name = str[index];
char first = name.charAt(0);
char last = name.charAt(name.length()-1);
int mid = 0;
if(first != last)
{
mid = ( ((int)(first) + ((int)(last)) / 2) );
}
else
{
mid = ( ((int)(first) + ((int)(last)) / 3) );
}
Random rNum = new Random();
int randomNum = rNum.nextInt(5);
String password = (first + "" + (char)(mid) + "" + randomNum).toLowerCase();
return password;
}
public void duplicateCheck(String[] password)
{
}
}
OUTPUT
Password Generator
Please enter 5 last names:
Please enter last name: magnum
Please enter last name: bauer
Please enter last name: sahid
Please enter last name: austen
Please enter last name: reese
sahid m?0
reese b?0
magnum s¥4
bauer a?0
austen r¤0
======================================================================
Please enter name to search (e or E to exit):sahid
Name: sahid ===> password: 0
++++++++++++++++++++++++++++++++++
//this line is supposed to print out "m?0" because it is the password
that was generated for "sahid" so why is it printing "0"? And how can I make it
print out "m?0" or whatever random password my program generates for it?
Your code is correct. Remember that password is the index of the psw[] String Array and not the actual content of the Array.
You just have to write psw[password] instead of password in the following line:
System.out.println("Name: " + input + " ===> " + "password: " + password);
/* Correction Here : Replace password --> psw[password] */
Corrected code snippet:
if(password >= 0)
{
System.out.println("Name: " + input + " ===> " + "password: " + psw[password]);
System.out.println("++++++++++++++++++++++++++++++++++");
}
Now, you should get output as follows:
Name: sahid ===> password: m?0
EDIT : Also, as mentioned by #Gyanapriya you'll have to sort psw[] array in addition to the lname[] unless you are trying to assign the random passwords to the users.

My code is not printing

my code (reads a text file, uses a class I built to sort through the data, and then outputs onto console), is not printing anything! Can somebody please tell me where my little mistake is! I know the VERY end is not finished yet. Please help!!!!!!!!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<Product>();
// Enter file name
System.out.print("Enter database file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
System.out.println();
while (inputFile.hasNext()) {
Product p = new Product();
String title = inputFile.nextLine();
String code = inputFile.nextLine();
Integer quantity = inputFile.nextInt();
Double price = inputFile.nextDouble();
inputFile.nextLine();
String type = inputFile.nextLine();
Integer userReview = inputFile.nextInt();
// read in title
p.setName(title);
// read in iCode
p.setInventoryCode(code);
// read in quantity
p.setQuantity(quantity);
// read in price
p.setPrice(price);
// read in type
p.setType(type);
// read in user reviews
while (!userReview.equals(-1)) {
p.addUserRating(userReview);
userReview = inputFile.nextInt();
}
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
inputFile.close();
} catch (IOException e) {
System.out.println("There was an error reading from " + fileName);
}
}
private static String highRating(ArrayList<Product> p) {
int highestR = 0;
int indexOfHighestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() > highestR) {
highestR = p.get(i).getAvgUserRating();
indexOfHighestR = i;
}
}
int zero = 0;
String Star = " ";
while (highestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfHighestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static String lowestRating(ArrayList<Product> p) {
int lowestR = 0;
int indexOfLowestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() < lowestR) {
lowestR = p.get(i).getAvgUserRating();
indexOfLowestR = i;
}
}
int zero = 0;
String Star = " ";
while (lowestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfLowestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static double maxDollar(ArrayList<Product> p) {
double largestP = 0;
int indexOfLargestP = 0;
for (int i = 0; i < p.size(); i++) {
double price = p.get(i).getPrice();
if (p.get(i).getPrice() > largestP) {
largestP = p.get(i).getPrice();
indexOfLargestP = i;
}
}
return largestP;
}
private static int minDollar(ArrayList<Product> p) {
double smallestP = p.get(0).getPrice();
int indexOfSmallestP = 0;
for (int i = 0; i < p.size(); i++) {
if (p.get(i).getPrice() < smallestP) {
smallestP = p.get(i).getPrice();
indexOfSmallestP = i;
}
}
return indexOfSmallestP;
}
private static void inventoryList(ArrayList<Product> p) {
int count =
System.out.println("Product Summary Report: ");
System.out
.println("------------------------------------------------------------");
for (int i = 0; i < count; i++) {
System.out.println("Title: " + p.get(i).getName());
System.out.println("I Code: " + p.get(i).getInventoryCode());
System.out.println("Product Type: " + p.get(i).getType());
System.out.println("Rating: " + p.get(i).getAvgUserRating());
System.out.println("# Rat.: " + p.get(i).getUserRatingCount());
System.out.println("Quantity: " + p.get(i).getQuantity());
System.out.println("Price: " + p.get(i).getPrice());
System.out.println();
}
System.out
.println("-----------------------------------------------------------------");
// System.out.println("Total products in database: " + count);
System.out.println("Highest total dollar item: "
+ p.get(maxDollar(p)) + " ($"+ p.(maxDollar(p)) + ")");
System.out.println("Smallest quantity item: "
+ p.get(minQuantity(quantities)) + " ("
+ types.get(minQuantity(quantities)) + ")");
System.out.println("Lowest total dollar item: "
+ titles.get(minDollar(prices)) + " ($"
+ prices.get(minDollar(prices)) + ")");
System.out
.println("-----------------------------------------------------------------");
}
First...
After you've create an instance of Product, p, you will need to add it to the products list, otherwise you will lose it's reference and won't be able to use it again...
while (inputFile.hasNext()) {
Product p = new Product();
//...
products.add(p);
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
Second...
You will need to pass the products List to something that want's to use/display the information, for example inventoryList...
But wait, that's not working?
If we take a closer look at the the inventoryList method...
int count = 0;
//...
for (int i = 0; i < count; i++) {
We can see that count is always 0, so it will never print anything! You should be using p.size() instead, which is the actually length of the products List
//...
for (int i = 0; i < p.size(); i++) {

Exception in thread "main" java.lang.NoSuchMethodError: main

Below is my code, and there are no errors in the actual code, but it won't run and I am not sure how to fix it. I have been working on this assignment for hours and keep receiving the same error in the output box over and over.
import java.util.Scanner;
public class whatTheGerbils
{
public static void main(String[] args)
{
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
Gerbil[] gerbilArray;
Food[] foodArray;
int numGerbils;
int foodnum;
public whatTheGerbils() {}
public void gerbLab()
{
boolean gerbLab = true;
while(gerbLab)
{
foodnum = 0;
numGerbils = 0;
String nameOfFood = "";
String colorOfFood;
int maxAmount = 0;
String ID;
String name;
String onebite;
String oneescape;
boolean bite = true;
boolean escape = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
int foodnum = Integer.parseInt(keyboard.nextLine());
foodArray = new Food[foodnum];
for (int i = 0; i < foodnum; i++)
{
System.out.println("The name of food item " + (i+1) + ":"); //this is different
nameOfFood = keyboard.nextLine();
System.out.println("The color of food item " + (i+1) + ":");
colorOfFood = keyboard.nextLine();
System.out.println("Maximum amount consumed per gerbil:");
maxAmount = keyboard.nextInt();
keyboard.nextLine();
foodArray[i] = new Food(nameOfFood, colorOfFood, maxAmount);
}
System.out.println("How many gerbils are in the lab?");
int numGerbils = Integer.parseInt(keyboard.nextLine()); // this is different
gerbilArray = new Gerbil[numGerbils];
for (int i = 0; i < numGerbils; i++)
{
System.out.println("Gerbil " + (i+1) + "'s lab ID:");
ID = keyboard.nextLine();
System.out.println("What name did the undergrads give to "
+ ID + "?");
name = keyboard.nextLine();
Food[] gerbsBetterThanMice = new Food[foodnum];
int foodType = 0;
for(int k = 0; k < foodnum; k++)
{
boolean unsound = true;
while(unsound)
{
System.out.println("How much " + foodArray[k].getnameOfFood() + "does" + name + " eat?");
foodType = keyboard.nextInt();
keyboard.nextLine();
if(foodType <= foodArray[k].getamtOfFood())
{
unsound = false;
}
else
{
System.out.println("try again");
}
}
gerbsBetterThanMice[k] = new Food(foodArray[k].getnameOfFood(), foodArray[k].getcolorOfFood(), foodType);
}
boolean runIt = true;
while (runIt)
{
System.out.println("Does " + ID + "bite? (Type in True or False)");
onebite = keyboard.nextLine();
if(onebite.equalsIgnoreCase("True"))
{
bite = true;
runIt = false;
}
else if (onebite.equalsIgnoreCase("False"))
{
bite = false;
runIt = false;
}
else {
System.out.println("try again");
}
}
runIt = true;
while(runIt)
{
System.out.println("Does " + ID + "try to escape? (Type in True or False)");
oneescape = keyboard.nextLine();
if(oneescape.equalsIgnoreCase("True"))
{
escape = true;
runIt = false;
}
else if(oneescape.equalsIgnoreCase("False"))
{
escape = false;
runIt = false;
}
else
{
System.out.println("try again");
}
}
gerbilArray[i] = new Gerbil(ID, name, bite, escape, gerbsBetterThanMice);
}
for(int i = 0; i < numGerbils; i++)
{
for(int k = 0; k < numGerbils; k++)
{
if(gerbilArray[i].getID().compareTo(gerbilArray[k].getID()) >
0)
{
Gerbil tar = gerbilArray[i];
gerbilArray[i] = gerbilArray[k];
gerbilArray[k] = tar;
}
}
}
boolean stop = false;
String prompt = "";
while(!stop)
{
System.out.println("Which function would you like to carry out: average, search, restart, or quit?");
prompt = keyboard.nextLine();
if (prompt.equalsIgnoreCase("average"))
{
System.out.println(averageFood());
}
else if (prompt.equalsIgnoreCase("search"))
{
String searchForID = "";
System.out.println("What lab ID do you want to search for?");
searchForID = keyboard.nextLine();
Gerbil findGerbil = findThatRat(searchForID);
if(findGerbil != null)
{
int integer1 = 0;
int integer2 = 0;
for (int i = 0; i < numGerbils; i++)
{
integer1 = integer1 + foodArray[i].getamtOfFood();
integer2 = integer2 + findGerbil.getGerbFood()[i].getamtOfFood();
}
System.out.println("Gerbil name: " +
findGerbil.getName() + " (" + findGerbil.getBite() + ", " +
findGerbil.getEscape() + ") " +
Integer.toString(integer2) + "/" + Integer.toString(integer1));
}
else
{
System.out.println("error");
}
}
else if (prompt.equalsIgnoreCase("restart"))
{
stop = true;
break;
}
else if(prompt.equalsIgnoreCase("quit"))
{
System.out.println("program is going to quit");
gerbLab = false;
stop = true;
keyboard.close();
}
else
{
System.out.println("error, you did not type average, search, restart or quit");
}
}
}
}
public String averageFood()
{
String averageStuff = "";
double avg = 0;
double num1 = 0;
double num2 = 0;
for (int i = 0; i < numGerbils; i++)
{
averageStuff = averageStuff + gerbilArray[i].getID();
averageStuff = averageStuff + " (";
averageStuff = averageStuff + gerbilArray[i].getName();
averageStuff = averageStuff + ") ";
for (int k = 0; k < foodnum; k++)
{
num1 = num1 + foodArray[k].getamtOfFood();
num2 = num2 + gerbilArray[i].getGerbFood()[k].getamtOfFood();
}
avg = 100*(num2/num1);
avg = Math.round(avg);
averageStuff = averageStuff + Double.toString(avg);
averageStuff = averageStuff + "%\n";
}
return averageStuff;
}
public Gerbil findThatRat (String ID)
{
for(int i = 0; i < numGerbils; i++)
{
if(ID.contentEquals(gerbilArray[i].getID()))
{
return gerbilArray[i];
}
}
return null;
}
}
Whenever a Java program runs, it starts with a method called main. You are getting the error because you don't have such a method. If you write such a method, then what it needs to do is this.
Create an object of the whatTheGerbils class.
Run the gerbLab() method for the object that was created.
The simplest way to do this would be to add the following code inside the whatTheGerbils class.
public static void main(String[] args){
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
You need a main method in your code for it to run, add in something like this
public static void main(String [] args){
gerLab();
}

Java arraylist retrieving data min/max values

I am doing my Java homework for a class. I wrote the below store program that the user inputs a 4 digit id and what money they had for that store id. This information get's put in an array. totals and store id's are retrieved.
in the next part of my program I am to retrieve min and max values from each data group:even and odd store id numbers. I have tried to do this by retrieving the origonal data and putting them into a new array. even data into an even array and odd data into an odd array. in the following code I am testing the even part. Once it works I will replicate in the odd section.
Right now the following code skips my request. I don't know how to fix this.
Any insight would be greatly appreciated!
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Bonus
{
public static void main (String[] arg)
{
Scanner in = new Scanner(System.in);
String storeID, highID;
double grandTotalSales = 0;
double evenGrandTotal = 0;
double oddGrandTotal = 0;
double evenTotalSale;
double oddTotalSale;
double largestYet = 0;
double maxValue = 0;
int numPenn, numNick, numDime, numQuar, numHalf, numDol;
boolean more = true;
boolean report = true;
String input;
int inputopt;
char cont;
char check1, highStoreID;
Store myStore;
ArrayList<Store> storeList = new ArrayList<Store>();
ArrayList<Store> evenStoreList = new ArrayList<Store>();
while(more)
{
in = new Scanner(System.in);
System.out.println("Enter 4 digit store ID");
storeID = in.nextLine();
System.out.println("Enter num of Penny");
numPenn = in.nextInt();
System.out.println("Enter num of Nickel");
numNick = in.nextInt();
System.out.println("Enter num of Dime");
numDime = in.nextInt();
System.out.println("Enter num of Quarter");
numQuar = in.nextInt();
System.out.println("Enter num of Half dollars");
numHalf = in.nextInt();
System.out.println("Enter num of Dollar bills");
numDol = in.nextInt();
myStore = new Store(storeID, numPenn, numNick, numDime, numQuar, numHalf, numDol);
storeList.add(myStore);
in = new Scanner(System.in);
System.out.println("More stores: Yes or No");
input = in.nextLine();
cont = input.charAt(0);
if((cont == 'N')||(cont == 'n'))
more = false;
}
while(report)
{
in = new Scanner(System.in);
System.out.println("What would you like to do? \nEnter: \n1 print Odd Store ID's report \n2 print Even Store ID's report \n3 to Exit");
inputopt = in.nextInt();
if(inputopt == 2)
{
System.out.println("\nEven Store ID's Report:");
System.out.println("Store ID" + " | " + " Total Sales" + " | " + "Even Total Sales");
for(int i = 0; i < storeList.size(); ++i)
{
myStore = (Store)(storeList.get(i));
storeID = myStore.getStoreID();
check1 = storeID.charAt(3);
if(check1 == '0' || check1 == '2' || check1 == '4'|| check1 == '6' || check1 =='8')
{
myStore.findEvenValue();
evenTotalSale = myStore.getEvenValue();
evenGrandTotal = evenGrandTotal + Store.getEvenValue();
System.out.println((storeList.get(i)).getStoreID() + " | " + (storeList.get(i)).getEvenValue() + " | " + (storeList.get(i)).getEvenGrandValue());
}
}
in = new Scanner(System.in);
System.out.println("Do want to print the highest and lowest sales? \nEnter yes or no");
input = in.nextLine();
cont = input.charAt(0);
if((cont == 'Y')||(cont == 'y'))
{
evenTotalSale = 0;
for(int i = 1; i < evenStoreList.size(); ++i)
{
myStore = (Store)(evenStoreList.get(i));
highID = myStore.getStoreID();
myStore.findEvenValue();
largestYet = myStore.getEvenValue();
if(largestYet > evenTotalSale)
{
Collections.copy(storeList, evenStoreList);
System.out.println("Store ID with highest sales is: ");
System.out.println((evenStoreList.get(i)).getStoreID() + " | " + largestYet);
}
}
}
else if((cont == 'N')||(cont == 'n'))
report = true;
}
else
if(inputopt == 1)
{
System.out.println("\nOdd Store ID's Report:");
System.out.println("Store ID" + " | " + " Total Sales" + " | " + " Odd Total Sales");
for(int i = 0; i < storeList.size(); ++i)
{
myStore = (Store)(storeList.get(i));
storeID = myStore.getStoreID();
check1 = storeID.charAt(3);
if(check1 == '1' || check1 == '3' || check1 == '5'|| check1 == '7' || check1 =='9')
{
myStore.findOddValue();
oddTotalSale = myStore.getOddValue();
oddGrandTotal = oddGrandTotal + Store.getOddValue();
System.out.println((storeList.get(i)).getStoreID() + " | " + (storeList.get(i)).getOddValue() + " | " + (storeList.get(i)).getOddGrandValue());
}
}
}
else
if(inputopt == 3)
report = false;
} // close while report
}// close of main
} // close class
class store:
public class Store
{
private String storeID;
private int numPenn, numNick, numDime, numQuar, numHalf, numDol;
Coin penn = new Coin("Penn", 0.01);
Coin nick = new Coin("Nickel", 0.05);
Coin dime = new Coin("Dime", 0.10);
Coin quar = new Coin("Quar", 0.25);
Coin half = new Coin("Half", 0.50);
Coin dol = new Coin("Dollar", 1.00);
private static double evenTotalSale;
private static double oddTotalSale;
static double evenGrandTotal = 0;
static double oddGrandTotal = 0;
public Store (String storeID, int numPenn, int numNick, int numDime, int numQuar, int numHalf, int numDol)
{
this.storeID = storeID;
this.numPenn = numPenn;
this.numNick = numNick;
this.numDime = numDime;
this.numQuar = numQuar;
this.numHalf = numHalf;
this.numDol = numDol;
}
public void findEvenValue()
{ evenTotalSale = numPenn * penn.getValue() + numNick * nick.getValue() + numDime * dime.getValue()
+ numQuar * quar.getValue() + numHalf * half.getValue() + numDol * dol.getValue();
evenGrandTotal = evenGrandTotal + evenTotalSale;
}
public static double getEvenValue()
{
return evenTotalSale;
}
public void findOddValue()
{ oddTotalSale = numPenn * penn.getValue() + numNick * nick.getValue() + numDime * dime.getValue()
+ numQuar * quar.getValue() + numHalf * half.getValue() + numDol * dol.getValue();
oddGrandTotal = oddGrandTotal + oddTotalSale;
}
public static double getOddValue()
{
return oddTotalSale;
}
public static double getOddGrandValue()
{
return oddGrandTotal;
}
public static double getEvenGrandValue()
{
return evenGrandTotal;
}
public String getStoreID()
{
return storeID;
}
}
your evenStoreList is empty.

Categories

Resources