I think a code is missing or not working because there should be a discount if the number is more than 5. For example a novel is borrowed for 6 days and so the rental charge should 8250. But isn't working as the rental charge is 9000.
Here is my program code:
**import java.util.Scanner;
class BookRentalShop
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of data you want to see: ");
int inputnum = sc.nextInt();
sc.nextLine();
System.out.println("");
String[] Name = new String[inputnum];
String[] Bookname = new String[inputnum];
String[] AuthorName = new String[inputnum];
String[] Booktype = new String[inputnum];
int[] NumbersofDaysBorrowed = new int[inputnum];
int[] RentalCharges = new int[inputnum];
String[] Types = {"Cartoon","Magazine", "Short story", "Long story", "Journal", "Novel", "Encyclopedia"};
int[] count = new int[7];
for (int d = 0; d < inputnum; d = d + 1)
{
System.out.println("Enter the name of the person:");
Name[d] = sc.nextLine();
System.out.println("Enter the bookname:");
Bookname[d] = sc.nextLine();
System.out.println("Enter the author's name:");
AuthorName[d] = sc.nextLine();
System.out.println("Enter the book type:");
Booktype[d] = sc.nextLine();
for (int k = 0; k < 7; k++)
{
if (Booktype[d].equals(Types[k]))
{
count[k]++;
}
}
System.out.println("Enter the number of days that the book had been borrowed:");
NumbersofDaysBorrowed[d] = sc.nextInt();
sc.nextLine();
if (Booktype[d].equalsIgnoreCase("Cartoon"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Magazine"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1000;
} else if (Booktype[d].equalsIgnoreCase("Short story"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Long story"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else if (Booktype[d].equalsIgnoreCase("Journal"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 350;
} else if (Booktype[d].equalsIgnoreCase("Novel"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 2500;
}
}
System.out.printf("%s %20s %20s %20s %20s %20s %20s\n", "No", "Name", "Bookname", "AuthorName", "Booktype", "Numbers of Days Borrowed", "Rental Charges");
for (int d = 0; d < inputnum; d = d + 1)
{
int num = d + 1;
System.out.printf("%s %20s %20s %20s %20s %20d %20d\n", num, Name[d], Bookname[d], AuthorName[d], Booktype[d], NumbersofDaysBorrowed[d], RentalCharges[d]);
}
String again = "Yes";
String exist = "No";
while (again.equals("Yes")) {
exist = "No";
System.out.println("enter search name");
String searchname = sc.nextLine();
for (int d = 0; d < inputnum; d = d + 1) {
if (searchname.equals(Name[d])) {
System.out.println("Name : " + Name[d]);
System.out.println("Bookname : " + Bookname[d]);
System.out.println("Number of Days : " + NumbersofDaysBorrowed[d]);
exist = "Yes";
}
}
if (exist.equals("No")) {
System.out.println("The search name is not found");
}
System.out.println("Do you want to search again? (Yes,No) ");
again = sc.nextLine();
}
int max = count[0];
for (int d = 0; d < 7; d = d + 1)
{
for (int k = d + 1; k < 7; k = k + 1)
{
if (count[k] > count[d])
{
max = count[k];
}
else {
max = count[d];
}
}
}
System.out.println("");
System.out.println("The most rented book is: " + max);
System.out.println("");
}
}
Outcome of the program:
No Name Bookname AuthorName Booktype Numbers of Days Borrowed Rental Charges
1 ghjghj hjghjgh hfghg Journal 3 1050
2 hghjhgjhgj uyiuyjghjg ghytghghjg Novel 6 9000
3 bcvnvn dasdasd weqwew Cartoon 5 2500*
I would appreciate it if anyone can help me find this problem.
I suggest solution like below:
This is the fragment of your code:
System.out.println("Enter the number of days that the book had been borrowed:");
NumbersofDaysBorrowed[d] = sc.nextInt();
sc.nextLine();
if (Booktype[d].equalsIgnoreCase("Cartoon")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Magazine")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1000;
} else if (Booktype[d].equalsIgnoreCase("Short story")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Long story")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else if (Booktype[d].equalsIgnoreCase("Journal")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 350;
} else if (Booktype[d].equalsIgnoreCase("Novel")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 2500;
}
And under this code try to add this. It replace in array calculated cost of book reduced by discount which is e.g 750 when number of days is more than 5. You can change it like you want
if(NumbersofDaysBorrowed[d] > 5)
{
int bookCost = RentalCharges[d] / NumbersofDaysBorrowed[d];
RentalCharges[d] = (5 * bookCost) + ((NumbersofDaysBorrowed[d] - 5) * (bookCost / 2)); // DISCOUNT
}
Related
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);
}
I am working on a project for my programming class and I am having trouble with the BufferedReader. Here is the code. It will run fine but it is only reading every other line in my csv file. I think the issue is I have inFile = input.readLine in there twice but if I remove one of them the I get runtime errors.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.io.BufferedReader;
public class CrimeData {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader input = new BufferedReader(new FileReader("crime.csv"));
String inFile;
try {
inFile = input.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int n = 0;
int year[] = new int[50], population[] = new int[50], violentCrime[] = new int[50];
double violentCrimeRate[] = new double[50];
int murderAndNonnegligentManslaughter[] = new int[50];
double murderAndNonnegligentManslaughterRate[] = new double[50];
int rape[] = new int[50];
double rapeRate[] = new double[50];
int robbery[] = new int[50];
double robberyRate[] = new double[50];
int aggravatedAssault[] = new int[50];
double aggravatedAssaultRate[] = new double[50];
int propertyCrime[] = new int[50];
double propertyCrimeRate[] = new double[50];
int burglary[] = new int[50];
double burglaryRate[] = new double[50];
int larcenyTheft[] = new int[50];
double larcenyTheftRate[] = new double[50];
int motorVehicleTheft[] = new int[50];
double motorVehicleTheftRate[] = new double[50];
try {
while ((inFile = input.readLine()) != null) {
String words[] = input.readLine().split(",");
year[n] = Integer.parseInt(words[0]);
population[n] = Integer.parseInt(words[1]);
violentCrime[n] = Integer.parseInt(words[2]);
violentCrimeRate[n] = Double.parseDouble(words[3]);
murderAndNonnegligentManslaughter[n] = Integer.parseInt(words[4]);
murderAndNonnegligentManslaughterRate[n] = Double.parseDouble(words[5]);
rape[n] = Integer.parseInt(words[6]);
rapeRate[n] = Double.parseDouble(words[7]);
robbery[n] = Integer.parseInt(words[8]);
robberyRate[n] = Double.parseDouble(words[9]);
aggravatedAssault[n] = Integer.parseInt(words[10]);
aggravatedAssaultRate[n] = Double.parseDouble(words[11]);
propertyCrime[n] = Integer.parseInt(words[12]);
propertyCrimeRate[n] = Double.parseDouble(words[13]);
burglary[n] = Integer.parseInt(words[14]);
burglaryRate[n] = Double.parseDouble(words[15]);
larcenyTheft[n] = Integer.parseInt(words[16]);
larcenyTheftRate[n] = Double.parseDouble(words[17]);
motorVehicleTheft[n] = Integer.parseInt(words[18]);
motorVehicleTheftRate[n] = Double.parseDouble(words[19]);
n++;
}
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("********** Welcome to the US Crime Statistical Application **************************");
System.out.println("Enter the number of the question you want answered. ");
System.out.println("1. What were the percentages in population growth for each consecutive year from 1994 – 2013?");
System.out.println("2. What year was the Murder rate the highest?");
System.out.println("3. What year was the Murder rate the lowest?");
System.out.println("4. What year was the Robbery rate the highest?");
System.out.println("5. What year was the Robbery rate the lowest?");
System.out.println("6. What was the total percentage change in Motor Vehicle Theft between 1998 and 2012?");
System.out.println("7. What was [enter your first unique statistic here]?");
System.out.println("8. What was [enter your second unique statistic here]?");
System.out.println("9. Quit the program");
System.out.println("Enter your selection: ");
int choice = scan.nextInt();
double low, high, percent;
int y;
switch (choice) {
case 1:
for (int i = 1; i < n; i++) {
percent = ((population[i] - population[i - 1]) / population[i - 1]) * 100;
System.out.println(
"Percentage of population growth during " + year[i - 1] + "-" + year[i] + " :" + percent);
}
break;
case 2:
high = murderAndNonnegligentManslaughter[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (murderAndNonnegligentManslaughter[i] > high) {
high = murderAndNonnegligentManslaughter[i];
y = year[i];
}
}
System.out.println("The year has the highest Murder rate : " + y);
break;
case 3:
low = murderAndNonnegligentManslaughter[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (murderAndNonnegligentManslaughter[i] < low) {
low = murderAndNonnegligentManslaughter[i];
y = year[i];
}
}
System.out.println("The year has the lowest Murder rate : " + y);
break;
case 4:
high = robberyRate[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (robberyRate[i] > high) {
high = robberyRate[i];
y = year[i];
}
}
System.out.println("The year has the highest Robbery rate : " + y);
break;
case 5:
low = robberyRate[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (robberyRate[i] < low) {
low = robberyRate[i];
y = year[i];
}
}
System.out.println("The year has the lowest Robbery rate : " + y);
break;
case 6:
double rateChange = 0;
rateChange = (motorVehicleTheft[19] - motorVehicleTheft[5]);
System.out.println(motorVehicleTheft);
case 7:
break;
case 8:
break;
case 9:
System.out.println("Thank you for using the Crime Database");
System.exit(0);
}
}
}
}
Your guess is absolutely correct.
This skips because the first condition in your while loop reads a line,
while((infile = input.readLine()) != null){
but you do not do anything with the read-in line.
Then the next time you call
input.readLine();
You read the next line, but you actually do something with the line.
For further reference, try looking at this thread:
Java: How to read a text file
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.
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");
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.