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.
Related
I'm trying to get my program to take multiple different return statements so i can have a win split and lose rather than just win or lose and cant seem to figure out how to do it. My program is made to be able to have either you win and it doubles your bet that you made. If you tie you get your money back. if you lose you lose your bet. Ive gotten win and lose to work previously with using a booelean and returning true or false but needed a way to add in a way to do split.
I've tried multiple methods I've seen online but to no avail any help would be appreciated.
//Import Random Number Generator
import java.util.Random;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
private String Win;
private String Lose;
private String Split;
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
Win = "Win";
}
else if(sum < other.getSum()){
Lose = "Lose";
}
else if(sum == other.getSum()){
Split = "Split";
}
return Win;
}
}//end main
import java.util.Scanner;
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100;
int bet;
int winnings;
int multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
System.out.println(you.getWin());
if(you.getWin()){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else{
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}//end class
I expect to be able to get different return statements that way I can actually set a win aspect a lose aspect but also a split aspect if both players tie.
You have three results to return which are: WIN, LOSE and TIE right?
In that case you have to use three different variables like,
public String Win = "Win",Lose = "Lose",Split = "Split";
and use other variable to store result like result and return this result in getWin(). See below code:
import java.util.Random;
import java.util.Scanner;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
public String Win = "Win",Lose = "Lose",Split = "Split";
private String result = "";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end main
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100,bet,winnings,multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
String result = you.getWin(enemy);
System.out.println(result);
if(result == you.Win){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else if (result == you.Lose){
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}else{
System.out.println("You Split");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}
I'm trying to implement a DiceThrowingGame which works fine. I have 2 classes currently which are "Player" and "Game". The code for the Game class is as below:
package dice.throwing.game;
import java.util.Scanner;
public class Game {
private int winningPoints;
private Player player1, player2;
private boolean gameSetup;
private final String defaultWinningScore = "200";
public Game() {
this.setWinningPoints(200);
this.gameSetup = false;
}
private int readScore(Scanner scanner) {
String score = "";
try {
score = scanner.nextLine();
if (score.isEmpty()) {
score = this.defaultWinningScore;
}
} catch (Exception e) {
}
return Integer.parseInt(score);
}
private Player createPlayer(Scanner scanner) {
String name = null;
do {
try {
name = scanner.nextLine();
if (name.isEmpty()) {
System.err.println("Name cannot be empty. Try again: ");
}
} catch (Exception e) {
}
} while (name.isEmpty());
return new Player(name);
}
private void startGame(Scanner scanner) {
System.out.println("Enter first player's name: ");
player1 = createPlayer(scanner);
System.out.println("Enter second player's name: ");
player2 = createPlayer(scanner);
System.out.println("Maximum score to win (<Enter> to use default 200): ");
this.setWinningPoints(this.readScore(scanner));
this.gameSetup = true;
}
private void playOneRound() {
int p1r1, p1r2, p2r1, p2r2;
p1r1 = (int) (1 + ((Math.random() * 10) % 6));
p1r2 = (int) (1 + ((Math.random() * 10) % 6));
p2r1 = (int) (1 + ((Math.random() * 10) % 6));
p2r2 = (int) (1 + ((Math.random() * 10) % 6));
int p1Points, p2Points;
boolean p1Bonus = false, p2Bonus = false;
p1Points = p1r1 + p1r2;
p2Points = p2r1 + p2r2;
if (p1r1 == p1r2) {
p1Points *= 2;
p1Bonus = true;
}
if (p2r1 == p2r2) {
p2Points *= 2;
p2Bonus = true;
}
player1.setTotalPoints(player1.getTotalPoints() + p1Points);
player2.setTotalPoints(player2.getTotalPoints() + p2Points);
System.out.print(player1.getName() + " rolled " + p1r1 + " + " + p1r2 + ", and scored " + p1Points + " points");
if (p1Bonus)
System.out.println(" (BONUS!)");
else
System.out.println();
System.out.print(player2.getName() + " rolled " + p2r1 + " + " + p2r2 + ", and scored " + p2Points + " points");
if (p2Bonus)
System.out.println(" (BONUS!)");
else
System.out.println();
}
private void leaderBoard() {
int p1Points = player1.getTotalPoints();
int p2Points = player2.getTotalPoints();
if (p1Points == p2Points)
System.out.println("Both players have the same score (" + p1Points + ") at the moment");
else {
System.out.print(player1.getName() + "'s current score is " + p1Points);
if (p1Points > p2Points)
System.out.println(" <--- CURRENT LEADER!");
else
System.out.println();
System.out.print(player2.getName() + "'s current score is " + p2Points);
if (p1Points < p2Points)
System.out.println(" <--- CURRENT LEADER!");
else
System.out.println();
}
}
private void gameHelp() {
System.out.println("<ENTER SOME HELP TEXT HERE>");
}
private boolean isGameOver() {
int player1Points = player1.getTotalPoints();
int player2Points = player2.getTotalPoints();
if(player1Points == player2Points &&
player1Points > this.winningPoints) {
System.out.println("Game Over! It's a draw!");
return true;
} else if(player1Points > this.winningPoints && player1Points > player2Points) {
System.out.println("Game Over! " + player1.getName() + " is the winner!");
return true;
} else if(player2Points > this.winningPoints && player2Points > player1Points) {
System.out.println("Game Over! " + player2.getName() + " is the winner!");
return true;
}
return false;
}
private void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to my Dice-and-Roll Game!");
System.out.println("==============================");
System.out.println("(1) Start a new game");
System.out.println("(2) Play one round");
System.out.println("(3) Who is leading now?");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
if (!this.gameSetup && (choice == 2 || choice == 3)) {
System.err.println("Error : Players have not been setup");
choice = 0;
}
switch (choice) {
case 1:
this.startGame(scanner);
break;
case 2:
this.playOneRound();
break;
case 3:
this.leaderBoard();
break;
case 4:
this.gameHelp();
break;
case 5:
exit = true;
}
if(this.gameSetup && this.isGameOver()) {
System.out.println("Exiting now.. See you later!");
exit = true;
}
}
scanner.close();
}
public static void main(String[] args) {
Game game = new Game();
game.eventLoop();
}
public int getWinningPoints() {
return winningPoints;
}
public void setWinningPoints(int winningPoints) {
this.winningPoints = winningPoints;
}
}
But I want to move the DiceThrowing part of the code to another class called "Dice" which is this part:
private void playOneRound() {
int p1r1, p1r2, p2r1, p2r2;
p1r1 = (int) (1 + ((Math.random() * 10) % 6));
p1r2 = (int) (1 + ((Math.random() * 10) % 6));
p2r1 = (int) (1 + ((Math.random() * 10) % 6));
p2r2 = (int) (1 + ((Math.random() * 10) % 6));
Confused on whether to put the whole playOneRound() method or just the Math.Random line?
To keep responsibilities and abstractions separate:
I would have a method Dice.getNumber() which would return the result of
(int) (1 + ((Math.random() * 10) % 6));
You could also have a 2nd method that would return an array of dice throws with a nbOfThrows parameter.
Then the playOneRound() would involve the throw of the dice as many times as the games rules allow.
Ok, so I was assigned to make a Dice program that could be called to roll a dice and return the side it landed on. I got the Dice part of it done. However when I run my program, my if statement doesn't execute to increment Counter if both die equal 6. What is wrong with my program.
This is the main:
public class PairOfDice {
public static void main(String[] args) {
int Counter = 0;
Dice D1 = new Dice();
Dice D2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
D1.Roll();
D2.Roll();
if (D1.equals(6) && D2.equals(6))
{
Counter++;
}
else
{
System.out.print ("Dice 1 = " + D1 + " | ");
System.out.println ("Dice 2 = " + D2);
}
}
System.out.print ("There were " + Counter + " Box Cars");
}
}
And this is my Dice function:
public class Dice {
private int Side;
public Dice()
{
Roll();
}
public void Roll()
{
Side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(Side);
return A;
}
}
You seem to have missed what .Equals() means:
D1.equals(6)
D1 doesn't equal 6. D1 is an instance of a Dice object, and 6 is an integer. You need to determine if the integer value within D1 equals 6.
First, create a getter for that value on the Dice class:
public int getSide()
{
return Side;
}
Then use that in the comparisons:
if (D1.getSide() == 6 && D2.getSide() == 6)
You need to check if the value of the die equals the value 6. Right now you are comparing the value of dice object to a number which doesn't make sense. Override equals or provide a getter for the value of the die.
I figured it out All I did was change if (D1.equals(6) && D2.equals(6)) to if (D1.equals(6) && D2.equals(6)) and removed the else part of the if statement, and put the print out before the if statement.
This is the main:
public class PairOfDice {
public static void main(String[] args) {
int Counter = 0;
Dice D1 = new Dice();
Dice D2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
D1.Roll();
D2.Roll();
System.out.print ("Dice 1 = " + D1 + " | ");
System.out.println ("Dice 2 = " + D2);
if (D1.Side == 6 && D2.Side == 6)
{
Counter++;
}
}
System.out.print ("There were " + Counter + " Box Cars");
}
}
This is Dice:
public class Dice {
int Side;
public Dice()
{
Roll();
}
public void Roll()
{
Side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(Side);
return A;
}
}
Please try below logic
public class PairOfDice {
public static void main(String[] args) {
int counter = 0;
Dice d1 = new Dice();
Dice d2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
d1.roll();
d2.roll();
if (d1.getSide()==6 && d2.getSide()==6)
{
counter++;
}
else
{
System.out.print ("Dice 1 = " + d1 + " | ");
System.out.println ("Dice 2 = " + d2);
}
}
System.out.print ("There were " + counter + " Box Cars");
}
}
public class Dice {
private int side;
public Dice()
{
roll();
}
public void roll()
{
side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(side);
return A;
}
public int getSide() {
return side;
}
}
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.
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){
....
}