Java arraylist retrieving data min/max values - java

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.

Related

Changing my program to use ArrayList

So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}

(Java) Need help summing digits in sets of integers and applying them to a credit card verification algorithm

I have to create a java program that verifies a credit card number based on whether it is a Visa or MasterCard. I am required to read the card number as a single string with spaces in between each set of four digits (xxxx xxxx xxxx xxxx). There must be 16 digits. All the digits in the number must be totaled. Then, if sum%10=0, it is a valid Visa. If sum%10=1, it is a valid MasterCard. Any deviation from this results in an invalid message.
My problem is that once I run my current program, I enter the number and the card type, and then the program stops and won't continue. I'm not sure what I'm doing wrong here.
import java.util.Scanner;
public class Assignment4
{
public static void main (String[] args)
{
String cardNum;
String typeAnswer;
char cardType;
int testSum;
int modResult;
Scanner scan = new Scanner (System.in);
System.out.println("\t\t Credit Card Verification");
System.out.println("\t\t ========================");
System.out.println("Enter your card number <xxxx xxxx xxxx xxxx>: ");
cardNum = scan.nextLine();
if(cardNum.length()<19 || cardNum.length()>19)
{
System.out.println("Incorrect card number. Re-launch the program and enter a 16-digit card number");
System.exit(0);
}
else
{
System.out.println("Is your card Visa or MasterCard?");
typeAnswer = scan.next().toUpperCase();
cardType = answer.charAt(0);
String numSet1 = cardNum.substring(0,4);
String numSet2 = cardNum.substring(5,9);
String numSet3 = cardNum.substring(10,14);
String numSet4 = cardNum.substring(15,19);
int i = Integer.parseInt(numSet1);
int j = Integer.parseInt(numSet2);
int k = Integer.parseInt(numSet3);
int l = Integer.parseInt(numSet4);
int sum1=0;
while(i>0)
{
sum1 = sum1 + (i%10);
i = i/10;
}
int sum2 = 0;
while(j>0)
{
sum2 = sum2 + (j%10);
j = j/10;
}
int sum3 = 0;
while(k>0)
{
sum3 = sum3+ (k%10);
k = k/10;
}
int sum4 = 0;
while(l>0)
{
sum4 = sum4 + (l%10);
j = j/10;
}
testSum = sum1 + sum2 + sum3 + sum4;
modResult = testSum%10
if(modResult=0 && cardType=V)
{
System.out.println("Valid Visa card.");
}
else if (modResult=1 && cardType=M)
{
System.out.println("Valid MasterCard.");
}
else
{
System.out.println("Not a valid " + typeAnswer + " card. Re-launch and try again.");
}
}
}
}
answer is undefined. It should be typeAnswer.
A semicolon is missing after modResult = testSum%10.
The conditions in if statements are wrong:
Use == operator, not = operator, to compare values of primitive types.
Use Character literals 'V' and 'M' instead of undefined symbols V and M.
l is not updated in the 4th loop, so it will be an infinite loop if the 4th number is positive. j = j/10; should be l = l/10;.
Try this:
import java.util.Scanner;
public class Assignment4
{
public static void main (String[] args)
{
String cardNum;
String typeAnswer;
char cardType;
int testSum;
int modResult;
Scanner scan = new Scanner (System.in);
System.out.println("\t\t Credit Card Verification");
System.out.println("\t\t ========================");
System.out.println("Enter your card number <xxxx xxxx xxxx xxxx>: ");
cardNum = scan.nextLine();
if(cardNum.length()<19 || cardNum.length()>19)
{
System.out.println("Incorrect card number. Re-launch the program and enter a 16-digit card number");
System.exit(0);
}
else
{
System.out.println("Is your card Visa or MasterCard?");
typeAnswer = scan.next().toUpperCase();
cardType = typeAnswer.charAt(0);
String numSet1 = cardNum.substring(0,4);
String numSet2 = cardNum.substring(5,9);
String numSet3 = cardNum.substring(10,14);
String numSet4 = cardNum.substring(15,19);
int i = Integer.parseInt(numSet1);
int j = Integer.parseInt(numSet2);
int k = Integer.parseInt(numSet3);
int l = Integer.parseInt(numSet4);
int sum1=0;
while(i>0)
{
sum1 = sum1 + (i%10);
i = i/10;
}
int sum2 = 0;
while(j>0)
{
sum2 = sum2 + (j%10);
j = j/10;
}
int sum3 = 0;
while(k>0)
{
sum3 = sum3+ (k%10);
k = k/10;
}
int sum4 = 0;
while(l>0)
{
sum4 = sum4 + (l%10);
l = l/10;
}
testSum = sum1 + sum2 + sum3 + sum4;
modResult = testSum%10;
if(modResult==0 && cardType=='V')
{
System.out.println("Valid Visa card.");
}
else if (modResult==1 && cardType=='M')
{
System.out.println("Valid MasterCard.");
}
else
{
System.out.println("Not a valid " + typeAnswer + " card. Re-launch and try again.");
}
}
}
}
Note that there are more problems to be fixed in this program. For example, this program accepts -123 -456 -789 -147 as a valid Visa card.
In the line: cardType=answer.charAt(0); You have an error. The variable answer is undefined. It should be cardType=typeAnswer.charAt(0);
Next you have created an infinity loop ,i.e. the fourth loop
while(l>0)
{
sum4 = sum4 + (l%10);
j = j/10;
}
Another mistake was you were not using the equality in the if statement, instead you were assigning values to the variables.
The correct code would be as follows:
import java.util.*;
import java.io.*;
public class CreditCardVerification
{
public static void main (String[] args)
{
String cardNum;
String typeAnswer;
char cardType;
int testSum=0;
int r;
int modResult;
Scanner scan = new Scanner (System.in);
System.out.println("\t\t Credit Card Verification");
System.out.println("\t\t ========================");
System.out.println("Enter your card number <xxxx xxxx xxxx xxxx>: ");
cardNum = scan.nextLine();
if(cardNum.length()<19 || cardNum.length()>19)
{
System.out.println("Incorrect card number. Re-launch the program and enter a 16-digit card number");
System.exit(0);
}
else
{
System.out.println("Is your card Visa or MasterCard?");
typeAnswer = scan.next().toUpperCase();
cardType = typeAnswer.charAt(0);
String numSet1 = cardNum.substring(0,4);
String numSet2 = cardNum.substring(5,9);
String numSet3 = cardNum.substring(10,14);
String numSet4 = cardNum.substring(15,19);
int i = Integer.parseInt(numSet1);
int j = Integer.parseInt(numSet2);
int k = Integer.parseInt(numSet3);
int l = Integer.parseInt(numSet4);
int sum1=0;
while(i!=0)
{
sum1 = sum1 + (i%10);
i = i/10;
}
int sum2 = 0;
while(j!=0)
{
sum2 = sum2 + (j%10);
j = j/10;
}
int sum3 = 0;
while(k!=0)
{
sum3 = sum3+ (k%10);
k = k/10;
}
int sum4 = 0;
while(l!=0)
{
sum4 = sum4 + (l%10);
l = l/10;
}
testSum = sum1 + sum2 + sum3 + sum4;
modResult = testSum%10;
if((modResult==0) && (cardType=='V'))
{
System.out.println("Valid Visa card.");
}
else if ((modResult==1) && (cardType=='M'))
{
System.out.println("Valid MasterCard.");
}
else
{
System.out.println("Not a valid " + typeAnswer + " card. Re-launch and try again.");
System.exit(0);
}
}
}
}`
Try this code.Its not so different from the code given by MikeCat but this should solve your problem. Take caution that don't enter just any number and test the code. Try it with a valid Visa or MasterCard credit card.

How could i add up the values in each row of the array?

This is my task
I have the program, printing out the values in the arrays, that step does not need to be there, that is the last for loop. Instead of that I need add the rows up, value by value using the die class i have, the code is something.getFaceValue();.
Code is Below
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
int tempVar = 0;
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++)
{
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
int choice = scan.nextInt();
while(choice == 1)
{
if(totalRollDie < 5)
{
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.nextInt();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++)
{
finalDie[i][var] = tempDie[var];
}
}
for(int i = 0 ;i < playerCount ; i++) //prints out the values stored in the array. need to sum them instead.
{
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i])
{
System.out.println(de);
}
}
tempDie = null;
}
}
Anyone have any tips?
EDIT: Die class
public class Die
{
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Append following code into your existance code,
public static void main(String... s)
{
......
int score[][] = new int[playerCount][2];
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
// System.out.println(" --------- " + playerName[i] + " ------------ ");
int playerTotalScore = 0;
for(Die de : finalDie[i]){
// System.out.println(de);
playerTotalScore += de.getFaceValue();
}
score[i][0] = i;
score[i][1]=playerTotalScore;
}
tempDie = null;
System.out.println("------------- Participant Score Card -------------");
System.out.println("Index PlayerName Score");
for(int i = 0 ; i < score.length ; i++){
System.out.println(score[i][0] + " - " + playerName[score[i][0]] + " - " + score[i][1]);
}
int temp[][] = new int[1][2];
for(int i = 0 ; i< score.length; i++){
for(int j = i+1 ; j<score.length;j++){
if(score[i][1] < score[j][1]){
temp[0][0] = score[i][0];
temp[0][1] = score[i][1];
score[i][0] = score[j][0];
score[i][1] = score[j][1];
score[j][0] = temp[0][0];
score[j][1] = temp[0][1];
}
}
}
System.out.println("--------------------------------------------------------");
System.out.println("-----------------WINNER---------------------");
System.out.println(score[0][0] + " - " + playerName[score[0][0]] + " - " + score[0][1]);
System.out.println("--------------------------------------------------------");
} // end of main method...
If I understand your question well, you could store the value in a variable;
int[] mPlayerScores = new int[playerCount];
String name = "";
for(int i = 0 ;i < playerCount ; i++) //prints out the values stored in the array. need to sum them instead.
{
int playerScoreSum = 0;
name = playerName[i];
System.out.println(" --------- " + name + " ------------ ");
for(Die de : finalDie[i])
{
playerScoreSum += de;
}
// this should store the sums in an array
mPlayerScores[i] = playerScoreSum;
//display the result for each player outside the for-loop to avoid continous printing
System.out.println(playerScoreSum);
}
//finds the highest score
double max = mPlayerScores[0];
for (int j = 1; j< mPlayerScores.length; j++)
{
if (mPlayerScores[j] > max)
{
max = mPlayerScores[j];
}
}
System.out.println(name+" is the winner with " + max+ " score");

How can i use Empty String to terminate?

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.

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

Categories

Resources