Why am I getting an illegal start of expression here? - java

I'm getting an illegal start of expression on my public String makeChange(int amount) { method here.
I'm making a change dispensing program, and am kind of stuck here, I think I'm going about doing it right but am getting this error.
package changedispenser;
public class ChangeDispenser {
private static int quarters, dimes, nickels, pennies;
private static int penniesLeft, nickelsLeft, dimesLeft, quartersLeft;
private static int pennyRollsAdded = 1;
private static int nickelRollsAdded = 1;
private static int dimeRollsAdded = 1;
private static int quarterRollsAdded = 1;
public static final int PENNIES_PER_ROLL = 50;
public static final int NICKELS_PER_ROLL = 40;
public static final int DIMES_PER_ROLL = 50;
public static final int QUARTERS_PER_ROLL = 40;
public static void main(String[] args) {
public String makeChange(int amount) {
if (amount > 99 || amount < 0) {
System.out.println("");
}
quarters = amount / 25;
amount = amount % 25;
dimes = amount / 10;
amount = amount % 10;
nickels = amount / 5;
amount = amount % 5;
pennies = amount;
do {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: " + nickels);
}
if (pennies != 0) {
System.out.println(" Pennies: " + pennies);
}
//Fix this so that it outputs the appropriate change IE: 23 cents is 2 dimes 3 pennies
System.out.println("Coins Left:");
System.out.println("Quarters: " + quartersLeft);
System.out.println("Dimes: " + dimesLeft);
System.out.println("Nickels: " + nickelsLeft);
System.out.println("Pennies: " + penniesLeft);
System.out.println("Rolls Added: ");
System.out.println("Quarters: " + quarterRollsAdded);
System.out.println("Dimes: " + dimeRollsAdded);
System.out.println("Nickels: " + nickelRollsAdded);
System.out.println("Pennies: " + pennyRollsAdded);
} while (amount > 0 && amount <= 99);
return "Quarters: " + quarters + " Dime: " + dimes + " Nickels: " + nickels + " Pennies: " + pennies;
}
public int getPenniesLeft() {
return penniesLeft;
}
public void setPenniesLeft(int penniesLeft) {
this.penniesLeft = penniesLeft;
if (penniesLeft <= 0) {
pennyRollsAdded = pennyRollsAdded++;
}
}
public int getNickelsLeft() {
return nickelsLeft;
}
public void setNickelsLeft(int nickelsLeft) {
this.nickelsLeft = nickelsLeft;
if (nickelsLeft <= 0) {
nickelRollsAdded = nickelRollsAdded++;
}
}
public int getDimesLeft() {
return dimesLeft;
}
public void setDimesLeft(int dimesLeft) {
this.dimesLeft = dimesLeft;
if (dimesLeft <= 0) {
dimeRollsAdded = dimeRollsAdded++;
}
}
public int getQuartersLeft() {
return quartersLeft;
}
public void setQuartersLeft(int quartersLeft) {
this.quartersLeft = quartersLeft;
if (quartersLeft <= 0) {
quarterRollsAdded = quarterRollsAdded++;
}
}
public int getPennyRollsAdded() {
return pennyRollsAdded;
}
public void setPennyRollsAdded(int pennyRollsAdded) {
this.pennyRollsAdded = pennyRollsAdded;
}
public int getNickelRollsAdded() {
return nickelRollsAdded;
}
public void setNickelRollsAdded(int nickelRollsAdded) {
this.nickelRollsAdded = nickelRollsAdded;
}
public int getDimeRollsAdded() {
return dimeRollsAdded;
}
public void setDimeRollsAdded(int dimeRollsAdded) {
this.dimeRollsAdded = dimeRollsAdded;
}
public int getQuarterRollsAdded() {
return quarterRollsAdded;
}
public void setQuarterRollsAdded(int quarterRollsAdded) {
this.quarterRollsAdded = quarterRollsAdded;
}
}
new code, here it is
package changedispenser;
public class ChangeDispenser {
private static int quarters, dimes, nickels, pennies;
private static int penniesLeft, nickelsLeft, dimesLeft, quartersLeft;
private static int pennyRollsAdded = 1;
private static int nickelRollsAdded = 1;
private static int dimeRollsAdded = 1;
private static int quarterRollsAdded = 1;
public static final int PENNIES_PER_ROLL = 50;
public static final int NICKELS_PER_ROLL = 40;
public static final int DIMES_PER_ROLL = 50;
public static final int QUARTERS_PER_ROLL = 40;
public static void main(String[] args) {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: "+ nickels);
}
if (pennies !=0) {
System.out.println(" Pennies: " + pennies);
}
}
ChangeDispenser() {
quartersLeft = QUARTERS_PER_ROLL;
dimesLeft = DIMES_PER_ROLL;
nickelsLeft = NICKELS_PER_ROLL;
penniesLeft = PENNIES_PER_ROLL;
pennyRollsAdded = 1;
nickelRollsAdded = 1;
dimeRollsAdded = 1;
quarterRollsAdded = 1;
}
public int getPenniesLeft() {
return penniesLeft;
}
public void setPenniesLeft(int penniesLeft) {
this.penniesLeft = penniesLeft;
if (penniesLeft <= 0) {
pennyRollsAdded = pennyRollsAdded++;
}
}
public int getNickelsLeft() {
return nickelsLeft;
}
public void setNickelsLeft(int nickelsLeft) {
this.nickelsLeft = nickelsLeft;
if (nickelsLeft <= 0) {
nickelRollsAdded = nickelRollsAdded++;
}
}
public int getDimesLeft() {
return dimesLeft;
}
public void setDimesLeft(int dimesLeft) {
this.dimesLeft = dimesLeft;
if (dimesLeft <= 0) {
dimeRollsAdded = dimeRollsAdded++;
}
}
public int getQuartersLeft() {
return quartersLeft;
}
public void setQuartersLeft(int quartersLeft) {
this.quartersLeft = quartersLeft;
if (quartersLeft <= 0) {
quarterRollsAdded = quarterRollsAdded++;
}
}
public int getPennyRollsAdded() {
return pennyRollsAdded;
}
public void setPennyRollsAdded(int pennyRollsAdded) {
this.pennyRollsAdded = pennyRollsAdded;
}
public int getNickelRollsAdded() {
return nickelRollsAdded;
}
public void setNickelRollsAdded(int nickelRollsAdded) {
this.nickelRollsAdded = nickelRollsAdded;
}
public int getDimeRollsAdded() {
return dimeRollsAdded;
}
public void setDimeRollsAdded(int dimeRollsAdded) {
this.dimeRollsAdded = dimeRollsAdded;
}
public int getQuarterRollsAdded() {
return quarterRollsAdded;
}
public void setQuarterRollsAdded(int quarterRollsAdded) {
this.quarterRollsAdded = quarterRollsAdded;
}
public String makeChange(int amount) {
if (amount > 99 || amount < 0) {
System.out.println("");
}
quarters = amount / 25;
amount = amount % 25;
dimes = amount / 10;
amount = amount % 10;
nickels = amount / 5;
amount = amount % 5;
pennies = amount;
do {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: " + nickels);
}
if (pennies != 0) {
System.out.println(" Pennies: " + pennies);
}
} while (amount > 0 && amount <= 99);
return "Quarters: " + quarters + " Dime: " + dimes + " Nickels: " + nickels + " Pennies: " + pennies;
}
public void writeReport() {
System.out.println("Coins Left:");
System.out.println("Quarters: " + quartersLeft);
System.out.println("Dimes: "+ dimesLeft);
System.out.println("Nickels: " + nickelsLeft);
System.out.println("Pennies: " +penniesLeft);
System.out.println("Rolls Added: ");
System.out.println("Quarters: "+ quarterRollsAdded);
System.out.println("Dimes: " + dimeRollsAdded);
System.out.println("Nickels: " + nickelRollsAdded);
System.out.println("Pennies: " + pennyRollsAdded);
}
}
Here is a seperate driver class to run the program.
package changedispenser;
import java.util.Random;
public class ChangeDispenserDriver {
public static void main(String[] args) {
ChangeDispenser changeMachine = new ChangeDispenser();
Random rand = new Random();
int amount;
for (int i = 0; i < 1000; i++) {
amount = rand.nextInt(99) + 1;
System.out.println("Amount: " + amount + ": Change = " + changeMachine.makeChange(amount));
}
changeMachine.writeReport();
}
}

You're creating a method inside of another method, a no-no:
public static void main(String[] args) {
public String makeChange(int amount) {
This is one place where good code formatting helps. Your formatting is not so good with lack of regular and sensible indentation. Put in the effort to format your code well and it will pay you dividends.
For instance, you'd see immediately:
public static void main(String[] args) {
public String makeChange(int amount) {
//...
}
// ...
}
... that you're nesting methods.
Edit:
Regarding your latest code, I can't say that I went through all of it, but this is very dangerous:
do {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: " + nickels);
}
if (pennies != 0) {
System.out.println(" Pennies: " + pennies);
}
} while (amount > 0 && amount <= 99);
Your loop depends on amount changing to a value that allows the loop to end, but where do you actually change amount inside of the loop? If you don't change amount inside of the loop, how will it ever exit the loop. You don't, and so the loop could (and does) loop forever.

Hovercraft is right, the way you would fix it is to separate them
public static void main (String[]args){
System.out.println(makeChange(5));
}
public String makeChange(int amount){
....
}

Related

Java number guessing game, while-loop

I am making a guessing game which makes a random number between 1 and 200. Whenever I guess, the program will tell me if its too high or too low, then ask me to try again.
I'm supposed to put a "try again" input box inside my code. Now my code is only showing "your guess is too high/too low". I don't understand where and how to put it.
This is my code:
import static javax.swing.JOptionPane.*;
class Tallspill {
public int nyttTall() {
int tilfeldig = (int) (Math.random() * 201);
return tilfeldig;
}
public void visMelding(String melding) {
showMessageDialog(null,melding);
}
private void forLite(int tall) {
if (tall < nyttTall()) {
String melding = (tall + " er for lite. Prøv igjen!");
visMelding(melding);
}
}
private void forStort(int tall) {
if (tall>nyttTall()) {
String melding = (tall+" er for stort. Prøv igjen!");
visMelding(melding);
}
}
public void avsluttRunde(int antall, int tall) {
String melding = (tall + "er riktig. Du brukte " + antall + " forsøk.");
visMelding(melding);
}
public void kjørspill() {
int random = nyttTall();
int tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
int antall = 0;
while(tall != random) {
if (tall < random) {
forLite(tall);
//metode for nytt forsøk
}
antall++;
if (tall > random) {
forStort(tall);
//metode for nytt forsøk
}
antall++;
if (tall == random) {
avsluttRunde(antall,tall);
}
}
}
}
public class Test {
public static void main(String[] args) {
Tallspill spill = new Tallspill();
spill.kjørspill();
}
}
I tried putting an input string inside the while-loop, but then it just looped on "try again". I also tried putting it inside the toolow and toohigh methods, but then I got an error.
The issue in your solution.
After number is big or small you do not show the number input dialog again. Because that code is outside your while loop
int tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
I have refactored your code a bit.
public void kjørspill() {
int random = nyttTall();
int tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
int antall = 0;
while(tall != random) {
antall++;
if (tall < random) {
forLite(tall);
tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
//metode for nytt forsøk
} else if (tall > random) {
forStort(tall);
tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
//metode for nytt forsøk
}
}
avsluttRunde(antall,tall);
}
In your Numbergame class, the tooSmall() and tooBig() methods are always comparing against a new random number. The random number should be a class member variable that gets filled by the newNumber() method, for example:
public class Numbergame {
int randomNumber;
public int newNumber() {
this.randomNumber = (int) (Math.random() * 201);
return randomNumber;
}
private void tooSmall(int number) {
if (number < randomNumber) {
String message = (number + " is too low. Try again!");
showMessage(message);
}
}
private void tooBig(int number) {
if (number > randomNumber) {
String message = (number + " is too high. Try again!");
showMessage(message);
}
}
// rest of class code ...
Here is the entire class reworked. I have also added some input validation so to perhaps eliminate at least some obvious exceptions:
public class Numbergame {
int randomNumber;
public int newNumber() {
this.randomNumber = (int) (Math.random() * 201);
return randomNumber;
}
public void showMessage(String message) {
showMessageDialog(message);
}
private void tooSmall(int number) {
if (number < randomNumber) {
String message = (number + " is too low. Try again!");
showMessage(message);
}
}
private void showMessageDialog(String message) {
JOptionPane.showMessageDialog(null, message, "Just so you know...", JOptionPane.INFORMATION_MESSAGE);
}
private String showInputDialog(String message) {
return JOptionPane.showInputDialog(null, message, "User Input...", JOptionPane.QUESTION_MESSAGE);
}
private void tooBig(int number) {
if (number > randomNumber) {
String message = (number + " is too high. Try again!");
showMessage(message);
}
}
public void endRound(int tries, int number) {
String message = (number + " is CORRECT!. You used " + tries + " tries.");
showMessage(message);
}
public void playgame() {
int random = newNumber();
int tries = 0;
int number = -1;
while (number != random) {
tries++;
String userVal = "";
while (userVal.isEmpty()) {
userVal = showInputDialog("<html>Enter a number between "
+ "<font size='4' color=blue>0</font> and <font size='4' "
+ "color=blue>200</font>:<br><center><font color=gray>('q' "
+ "to quit)</font></center><br></html>");
if (userVal == null || userVal.isEmpty()) {
JOptionPane.showMessageDialog(null, "<html>You must enter <font size='4'>"
+ "<b>something!</b></font></html>",
"Invalid Entry!", JOptionPane.WARNING_MESSAGE);
userVal = "";
}
else if (userVal.equalsIgnoreCase("q")) {
if (JOptionPane.showConfirmDialog(null, "Are you sure you want to Quit?",
"Quit Application?", JOptionPane.YES_NO_OPTION) == 0){
System.exit(0);
}
else {
userVal = "";
}
}
else if (userVal.matches("\\d+")) {
number = Integer.parseInt(userVal);
if (number < 0 || number > 200) {
JOptionPane.showMessageDialog(null, "Invalid Entry! ("
+ number + ")Try again...", "Invalid Entry!",
JOptionPane.WARNING_MESSAGE);
userVal = "";
}
}
}
if (number < random) {
tooSmall(number);
}
else if (number > random) {
tooBig(number);
}
else if (number == random) {
endRound(tries, number);
}
}
}
}
And of course....to play the game:
Numbergame play = new Numbergame();
play.playgame();
Ask user inside infinite while block and exit if user canceled or guessed the number. Check if input number is correct. Remove over checking from Tallspill class methods.
import static javax.swing.JOptionPane.showInputDialog;
import static javax.swing.JOptionPane.showMessageDialog;
class Tallspill {
public int nyttTall() {
int tilfeldig = (int) (Math.random() * 201);
return tilfeldig;
}
public void visMelding(String melding) {
showMessageDialog(null, melding);
}
private void forLite(int tall) {
String melding = tall + " er for lite. Prøv igjen!";
visMelding(melding);
}
private void forStort(int tall) {
String melding = tall + " er for stort. Prøv igjen!";
visMelding(melding);
}
public void avsluttRunde(int antall, int tall) {
String melding = tall + "er riktig. Du brukte " + antall + " forsøk.";
visMelding(melding);
}
public void invalidNumber() {
String melding = "Invalid number. Try again.";
visMelding(melding);
}
public void kjrspill() {
int random = nyttTall();
int tall;
int antall = 0;
while (true) {
antall++;
String tallStr = showInputDialog("Skriv inn et tall mellom 0 og 200");
if (tallStr == null)
return;
try {
tall = Integer.parseInt(tallStr);
if (tall < random)
forLite(tall); //metode for nytt forsøk
if (tall > random)
forStort(tall); //metode for nytt forsøk
if (tall == random){
avsluttRunde(antall, tall);
return;
}
} catch (NumberFormatException ex) {
invalidNumber();
}
}
}
}
public class TestGuessNumber {
public static void main(String[] args) {
Tallspill spill = new Tallspill();
spill.kjrspill();
}
}

Java | how can I use multiple methods to print out grade scores?

import java.util.Scanner;
public class BA4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println("Total score is: " + (getTotalScore(storeGrades)));
System.out.println("Lowest score is: " + (getLowestScore(storeGrades)));
System.out.println("Highest score is: " + (getHighestScore(storeGrades)));
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
public static int getLowestScore(int[] storeGrades) {
int getLowestScore = 0;
for (int i = 0; i > storeGrades.length; i++) {
getLowestScore = storeGrades[i];
}
return getLowestScore;
}
public static int getHighestScore(int[] storeGrades) {
int getHighestScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
getHighestScore = storeGrades[i];
}
return getHighestScore;
}
public static double averageScore(double[] storeGrades) {
double averageScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
averageScore = (double) storeGrades[i];
}
return averageScore;
}
public static int printGrade(int[] storeGrades) {
int printGrade;
if (printGrade > 89) {
String gradeSoFar = "A";
System.out.println("Your grade so far is an " + gradeSoFar);
}
else if ((printGrade > 79) && (printGrade < 90)) {
String gradeSoFar = "B";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 69) && (printGrade < 80)) {
String gradeSoFar = "C";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 59) && (printGrade < 70)) {
String gradeSoFar = "D";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 0) && (printGrade < 60)) {
String gradeSoFar = "F";
System.out.println("Your grade so far is an " + gradeSoFar);
}
return printGrade;
}
}
I am trying to figure out where I am going wrong. I have a couple of errors which leads me to believe I really just don't understand methods as well as I thought I did.
The goal is to create 5 methods displaying to the user the total, lowest, highest and average scores, and then to print the letter grade. Thank you for your assistance to this noobie java coder! :)
You are passing in a String when you should be passing in a Double[] into averageScore function in this line:
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
and you did not initialize the printGrade variable inside the printGrade function, you need to give it an initial value if you are going to use it in a comparison.
That's all the errors that

Incorrect Math In Program, not sure why?

I am writing a simple program for class. I am not sure why the math is not showing correctly? When I ask for a tax and input 0.08 it is not computing to the right number. For example entering 1234.55 as the retail amount gives a transaction amount of 1266.6483 instead of the correct amount which should be 1333.31. Any help would be appreciated... I'll post the code below
package Project03Driver;
import java.io.*;
public class Project03Driver
{
public static void main(String args[]) throws IOException
{
Project03 app;
app = new Project03();
app.appMain();
}
}
class Project03
{
BufferedReader stdin;
int tNum, tCount, smallTnum;
double tax, rA, tA, raTot, disTot, taTot, taAvg, smallTa;
boolean disc;
String store, date, dFlag, inString;
public void appMain() throws IOException
{
rptInit();
displayHeader();
getStore();
while(tNum != 0)
{
salesData();
}
calcAvg();
rptOut();
}
void rptInit()
{
tNum = 1;
tCount = smallTnum = 0;
raTot = disTot = taTot = taAvg = 0;
smallTa = 10000;
stdin = new BufferedReader (new InputStreamReader(System.in));
}
void displayHeader()
{
System.out.println("Project #03 Solution");
System.out.println("Written by Jordan Hawkes");
}
void getStore() throws IOException
{
System.out.println("Enter Store: ");
store = stdin.readLine();
System.out.println("Enter Date: ");
date = stdin.readLine();
System.out.println("Enter Tax as Decimal (ex. .05): ");
tax = Double.parseDouble(stdin.readLine());
}
void salesData() throws IOException
{
getTransNum();
if (tNum != 0)
{
inputRa();
calcSalesData();
outputSalesData();
}
}
void getTransNum() throws IOException
{
System.out.println("Enter Transaction Number: ");
tNum = Integer.parseInt(stdin.readLine());
}
void inputRa() throws IOException
{
System.out.println("Enter Retail Amount: ");
rA = Double.parseDouble(stdin.readLine());
}
void calcSalesData()
{
tCount = tCount + 1;
raTot = raTot + rA;
if (tA > 1500)
{
disc = true;
dFlag = "Discounted";
}
else
{
disc = false;
dFlag = "No";
}
transAmt();
discTot();
taTot = taTot +tA;
smallTrans();
}
void transAmt()
{
if (disc = true)
{
tA = (rA * 0.95) + ((rA * 0.95) * tax);
}
else
{
tA = (rA * tax) + rA;
}
}
void discTot()
{
if (disc = true)
{
disTot = disTot + (tA - rA);
}
else
{
disTot = disTot;
}
}
void smallTrans()
{
if (tA < smallTa)
{
smallTa = tA;
smallTnum = tNum;
}
}
void outputSalesData()
{
System.out.println("");
System.out.println("--------------------------------------------");
System.out.println("Transaction Number: " + tNum);
System.out.println("Retail Amount: " + rA);
System.out.println("Discount Flag: " + dFlag);
System.out.println("Transaction Amount: " + tA);
System.out.println("--------------------------------------------");
System.out.println("");
}
void calcAvg()
{
taAvg = taTot / tCount;
}
void rptOut()
{
System.out.println("");
System.out.println("--------------------------------------------");
System.out.println("Store: " + store);
System.out.println("Date: " + date);
System.out.println("Tax Rate: " + tax);
System.out.println("--------------------------------------------");
System.out.println("Retail Amount Total: " + raTot);
System.out.println("Discount Total: " + disTot);
System.out.println("Transaction Amount Total: " + taTot);
System.out.println("Average Transaction Amount: " + taAvg);
System.out.println("Smallest Transaction Amount: " + smallTa);
System.out.println("Smallest Transaction Number: " + smallTnum);
System.out.println("--------------------------------------------");
}
}
if (disc = true)
should be
if (disc == true)
I think you should delete the question, because that is a typo. According to https://stackoverflow.com/help/on-topic

It just adds on

So for yet ANOTHER project I am doing an RPG code. Like Dungeons and dragons. My particular problem is the attributes. Basically the application gives statistics to the player and then, in case the player does not like the stats they have recieved, the application gives them the option to reroll. The first roll does fine, however, if the user chooses to reroll, the stats (both the first and the next) add on to each other. Here is my code:
The Main Method:
package bagOfHolding;
public class Advanced {
public static void main(String [] args){
GameMaster.game();
}
}
The Dice Class (this rolls the stats for the statistics):
package bagOfHolding;
import java.util.Random;
public class DiceBag {
private static int sum;
public static int rollD6() {
int[] Dice = new int[3];
Random num = new Random();
for (int i = 0; i < Dice.length; i++) {
Dice[i] = num.nextInt((6)) + 1;
}
for (int i : Dice) {
sum += i;
}
return sum;
}
// public static int getSum() {
// return sum;
// }
// public static void setSum(int sum) {
// DiceBag.sum = sum;
// }
}
The Game Master (This does the whole game):
package bagOfHolding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GameMaster {
public static void game() {
Hero.attributes();
}
public static void ReRoll() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Would you like to reroll your hero? 1) Yes or 2) No");
System.out.println("Please enter a number");
System.out.println("Any number other than 1 or 2 will exit the application");
try {
String userInput = delta.readLine();
int input = Integer.parseInt(userInput);
if (input == 1) {
Hero.setStrength(DiceBag.rollD6());
Hero.setDexterity(DiceBag.rollD6());
Hero.setIntelligence(DiceBag.rollD6());
Hero.attributes();
} else if (input == 2) {
System.exit(0);
} else {
System.exit(0);
}
} catch (NumberFormatException NFE) {
System.out.println("Invalid");
} catch (IOException IOE) {
System.out.println("Invalid");
}
}
}
And the Hero class (this has all the statistics):
package bagOfHolding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Hero {
/*
* Attributes - Randomly determined by 3d6
*
*/
/*
* -3 attributes - Strength - Damage bonus - If over 15 every pt = +1 (_++;)
* - Negative Damage Bonus - If under 10 every pt = -1 (_--;) - Dexterity
* -Strike bonus - every 2 pts over 14 = (_%2 + 1) - Negative Strike bonus -
* every 2 pts below 10 = (_%2 -1) - Dodge bonus - every 2 pts over 15 =
* (_%2 + 1) - Negative dodge bonus - every 2 pts below 11 = (_%2 -1) -
* Intelligence -Spell Strength Bonus - every pt over 15 = (++2) - Negative
* Spell Strength Bonus - every pt below 11 = (--2)
*
* Base Attributes - Health -Strength * 10 - MP - Intelligence *5
*/
private static int strength = DiceBag.rollD6();
private static int intelligence = DiceBag.rollD6();
private static int dexterity = DiceBag.rollD6();
public static int getIntelligence() {
return intelligence;
}
public static void setIntelligence(int intelligence) {
Hero.intelligence = intelligence;
}
public static int getDexterity() {
return dexterity;
}
public static void setDexterity(int dexterity) {
Hero.dexterity = dexterity;
}
public static int getStrength() {
return strength;
}
public static void setStrength(int strength) {
Hero.strength = strength;
}
public static void attributes() {
strength = getStrength();
System.out.println("Here is your hero: ");
// DiceBag.rollD6();
System.out.println("Strength = " + strength);
if (strength > 15) {
System.out.println("Damage Bonus = " + "+" + (strength - 15));
} else if (strength < 10) {
System.out.println("Negative Damage Bonus = " + "-" + (10 - strength));
} else {
System.out.println("You do not have damage bonus");
}
intelligence = getIntelligence();
System.out.println("Intelligence = " + intelligence);
if (intelligence > 15) {
System.out.println("Spell Strength Bonus = " + "+" + ((intelligence - 15) * 2));
} else if (strength < 11) {
System.out.println("Negative Spell Strength Bonus = " + "-" + ((11 - intelligence) * 2));
} else {
System.out.println("You do not have a spell strength bonus");
}
dexterity = getDexterity();
System.out.println("Dexterity = " + dexterity);
if (dexterity > 15 && dexterity % 2 == 0) {
System.out.println("Dodge Bonus = " + "+" + (dexterity - 15));
} else if (dexterity < 11 && dexterity % 2 == 0) {
System.out.println("Negative Dodge Bonus = " + "-" + (11 - dexterity));
} else {
System.out.println("You do not have a dodge bonus");
}
if (dexterity > 14 && dexterity % 2 == 0) {
System.out.println("Strike Bonus = " + "+" + (dexterity - 14));
} else if (dexterity < 10 && dexterity % 2 == 0) {
System.out.println("Negative Strike bonus = " + "-" + (10 - dexterity));
} else {
System.out.println("You do not have a strike bonus");
}
int health = strength * 10;
System.out.println("Health = " + health);
int MP = intelligence * 5;
System.out.println("MP = " + MP);
GameMaster.ReRoll();
}
}
DiceBag sum should be local to rollD6 rather than static.

Credit card type and validation

I would like to run a program that can determine the validation and type of credit card number based of number entered. Compiler shows notification that there is an error in my coding but I cannot detect where is it. The program is also cannot be run. Below is the coding,
import java.util.*;
public class CreditCard {
public static void main(String args[]) {
String CType;(String number) {
if (number.startsWith("4"))
return "Visa";
else if (number.startsWith("5"))
return "MasterCard";
else if (number.startsWith("6"))
return "Discover";
else if (number.startsWith("37"))
return "American Express";
else
return "Unknown type";
};
Scanner input = new Scanner(System.in);
System.out.println("Enter a credit card number: ");
long number = input.nextLong();
long total = sumOfEvenPlaces(number) + (sumOfOddPlaces(number)*2);
if (isValid(total)) {
System.out.println("The "+CType+" card number is valid");
} else {
System.out.println("The "+CType+" card number is invalid.");
}
}
public static boolean isValid(long total) {
if (total % 10 != 0) {
} else {
return true;
}
return false;
}
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int getDigit(int number) {
if (number > 9) {
return (number % 10 + number / 10);
}
return number;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
number /= 10;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
}
I do card type detection with an enum:
package com.gabrielbauman.gist;
import java.util.regex.Pattern;
public enum CardType {
UNKNOWN,
VISA("^4[0-9]{12}(?:[0-9]{3}){0,2}$"),
MASTERCARD("^(?:5[1-5]|2(?!2([01]|20)|7(2[1-9]|3))[2-7])\\d{14}$"),
AMERICAN_EXPRESS("^3[47][0-9]{13}$"),
DINERS_CLUB("^3(?:0[0-5]\\d|095|6\\d{0,2}|[89]\\d{2})\\d{12,15}$"),
DISCOVER("^6(?:011|[45][0-9]{2})[0-9]{12}$"),
JCB("^(?:2131|1800|35\\d{3})\\d{11}$"),
CHINA_UNION_PAY("^62[0-9]{14,17}$");
private Pattern pattern;
CardType() {
this.pattern = null;
}
CardType(String pattern) {
this.pattern = Pattern.compile(pattern);
}
public static CardType detect(String cardNumber) {
for (CardType cardType : CardType.values()) {
if (null == cardType.pattern) continue;
if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
}
return UNKNOWN;
}
}
You can then do CardType.detect("cardnumbergoeshere") and you'll get back CardType.VISA, etc.
There's a unit test over at the gist.
For validation, I have:
public boolean isValid(String cardNumber) {
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
That should do it.
Edit: fixed escape characters in DINERS_CLUB
This may be more along the lines of what you're trying to do:
public static void main(final String args[])
{
String cType = null;
System.out.println("Enter a credit card number: ");
final Scanner input = new Scanner(System.in);
final String cardNumber = input.next();
if (cardNumber.startsWith("4"))
{
cType = "Visa";
}
else if (cardNumber.startsWith("5"))
{
cType = "MasterCard";
}
else if (cardNumber.startsWith("6"))
{
cType = "Discover";
}
else if (cardNumber.startsWith("37"))
{
cType = "American Express";
}
else
{
cType = "Unknown type";
}
final long total = sumOfEvenPlaces(Long.valueOf(cardNumber)) + (sumOfOddPlaces(Long.valueOf(cardNumber)) * 2);
if (isValid(total))
{
System.out.println("The " + cType + " card number is valid");
}
else
{
System.out.println("The " + cType + " card number is invalid.");
}
}
On a stylistic note, CType should start with a lower case letter (e.g. cType). You'll have to experiment with the use of Scanner as well as I'm not sure my implementation will do what you're looking for.

Categories

Resources