I'm trying to make a casino program for my school project. Everything seems to work just fine except that the statement of the do-while loop inside the main() method is always skipped at the first, third, fifth (odd) lines in the console.
THE PROGRAM:
import java.util.Scanner;
import java.text.*;
import java.util.*;
public class Casino
{
public static Scanner input;
static final String SEPARATOR = "\n";
public static void main (String[] args) throws Exception
{
int winnings;
while (getBet() != 0)
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * getBet();
display(thePull, winnings);
}
System.out.println("Thanks");
}
//gets bet, stores in static class variables
public static int getBet()
{
final double MAX_BET = 50;
String prompt, strUserResponse;
int intResponse;
input = new Scanner(System.in);
do
{
prompt = "How much would you like to bet ( Min $1 - Max $50 ) "
+ "or press '0' to quit?";
System.out.print(prompt);
strUserResponse = input.nextLine();
intResponse = Integer.parseInt(strUserResponse);
}
while( intResponse < 0 || intResponse > MAX_BET );
return intResponse;
}
public static String randString()
{
int bar = 38;
int cherries = 78;
int space = 85;
int seven = 100;
String randomString = "";
int randomNum = 1 + (int)(Math.random() * 100);
if (randomNum <= bar)
randomString = "BAR";
else if (randomNum <= cherries)
randomString = "cherries";
else if (randomNum <= space)
randomString = "space";
else if (randomNum <= seven)
randomString = "7";
return randomString;
}
public static TripleString pull()
{
TripleString pullString = new TripleString();
String str1 = randString();
pullString.setString1(str1);
String str2 = randString();
pullString.setString2(str2);
String str3 = randString();
pullString.setString3(str3);
return pullString;
}
public static int getPayMultiplier (TripleString thePull)
{
if (thePull.getString1() == "cherries" &&
thePull.getString2() != "cherries" )
return 5;
else if (thePull.getString1() == "cherries" &&
thePull.getString2() == "cherries" &&
thePull.getString3() != "cherries")
return 15;
else if (thePull.getString1() == "cherries" &&
thePull.getString2() == "cherries" &&
thePull.getString3() == "cherries")
return 30;
else if (thePull.getString1() == "BAR" &&
thePull.getString2() == "BAR" &&
thePull.getString3() == "BAR")
return 50;
else if (thePull.getString1() == "7" &&
thePull.getString2() == "7" &&
thePull.getString3() == "7")
return 100;
else
return 0;
}
public static void display (TripleString thePull, int winnings)
{
System.out.println(SEPARATOR + ">>>Brrrrrr! Your Pull Is . . .<<<"
+ SEPARATOR + thePull.toString());
if ( winnings == 0)
System.out.println("Sorry you lose. . . GOOD LUCK NEXT TIME!"
+ SEPARATOR);
else
System.out.println("Congaratulations, you win =" + " $" + winnings
+ " !" + SEPARATOR + "YEAY !!! :):):)" + SEPARATOR);
}
}
class TripleString
{
//member data
private String string1, string2, string3;
//static constants
public static final double MIN_LEN = 1;
public static final double MAX_LEN = 50;
public static final String DEFAULT_STRING = "undefined";
//default constructor
TripleString ()
{
string1 = DEFAULT_STRING;
string2 = DEFAULT_STRING;
string3 = DEFAULT_STRING;
}
//parameter-taking constructor
TripleString (String str1, String str2, String str3)
{
if (! setString1(str1))
str1 = DEFAULT_STRING;
if (! setString2(str2))
str2 = DEFAULT_STRING;
if (! setString3(str3))
str3 = DEFAULT_STRING;
}
//private static helper method
private boolean validString(String str)
{
if (str == null || str.length() < MIN_LEN || str.length() > MAX_LEN)
return false;
else
return true;
}
//accessor set methods
public boolean setString1 (String stringName1)
{
if ( !validString(stringName1) )
return false;
string1 = stringName1;
return true;
}
public boolean setString2 (String stringName2)
{
if ( !validString(stringName2) )
return false;
string2 = stringName2;
return true;
}
public boolean setString3 (String stringName3)
{
if ( !validString(stringName3) )
return false;
string3 = stringName3;
return true;
}
//accessor get methods
public String getString1 () { return string1; }
public String getString2 () { return string2; }
public String getString3 () { return string3; }
public String toString ()
{
String reStr;
reStr = string1 + " "+ string2 + " " + string3;
return reStr;
}
}
Here is the example of my run:
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?1
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?6
//Brrrrr below supposed to have ">>>" "<<<" but I remove it manually in this example since it creates blockquotes
Brrrrrr! Your Pull Is . . .
cherries cherries BAR
Congaratulations, you win = $90 !
YEAY !!! :):):)
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?7
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?7
Brrrrrr! Your Pull Is . . .
7 BAR cherries
Sorry you lose. . . GOOD LUCK NEXT TIME!
I want to make it looks more like
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?1
Brrrrrr! Your Pull Is . . .<<<
BAR BAR BAR
Congaratulations, you win = $50 !
YEAY !!! :):):)
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?2
Brrrrrr! Your Pull Is . . .<<<
BAR cherries BAR
Sorry you lose. . . GOOD LUCK NEXT TIME!
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?0
I think the problem has to be related with the loop in my getInput() method, but I'm really not sure why. I know I could've not make a loop in the getInput() method, but my instructor specifies that the method has to loop until the user put the valid #(1-50)
I've tried changing it to the standard while loop or modifying the code in many other way, but in new ways come new problems. For example, if I change my main method to
Alternate main()
public static void main (String[] args) throws Exception
{
int bet = getBet(), winnings;
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
}
while (getBet() != 0);
System.out.println("Thanks");
}
If I use the above code for the main, my variable bet will stay the same for every loop since it has been initiated before that.
Edit: the alternate main() method
Edit2: Add more sample run
Your second main does not work, because you do not re-assign the bet variable.
Working simple alternate main()
public static void main (String[] args) throws Exception
{
int bet = getBet(), winnings;
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
bet = getBet();
}
while ( bet != 0);
System.out.println("Thanks");
}
Your first main does not work because you call getBet() twice
Working main
public static void main (String[] args) throws Exception
{
int winnings;
int bet;
while ((bet = getBet()) != 0)
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
}
System.out.println("Thanks");
}
If you want your bet variable to not remain the same, you can change the while loop to simply:
while(true){
//get the bet here
if(bet == 0){
break;
}
//Do the rest of your stuff here.
}
This will change the bet every iteration but still stop running if it is zero.
Related
I apologize in advance for my rudimentary code--I started coding a couple months ago.
I'm trying to code a text-based baking game where there's a limited number of combos/recipes (16), and the user has to try to unlock all of the cake combos in order to finish the game. When I try to run the code, when asked for the topping the user wants, no matter what input I type in, the code doesn't run past this part. The expected result would be to take both the flavor and topping and add them together to become the new string of cake.
[A screenshot of the described problem][1]
[1]: https://i.stack.imgur.com/bphyO.png
Another problem I had, but can't check if I still have it because the code won't run past the "topping user input" section, is that when the code runs to the section where it checks if the cake combo has already been found or not, inside the terminal it prints out the combo the user first found infinitely.
I'd really appreciate any help, thank you so much.
The code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Bakery
public ArrayList<String> aList = new ArrayList();
public static int achievements = 0;
static ArrayList<String> foundCakes = new <String>ArrayList();
public static String[] f = {"chocolate", "vanilla", "strawberry", "banana"};
public static String[] t = {"sprinkles", "fruit", "frosting", "nothing"};
public static void main (String[]args) throws InterruptedException {
Scanner sc = new Scanner(System.in);
System.out.println("(To quit the game, type in 'quit')");
delay("Hi, what's your name?", 60L);
String playerName = sc.nextLine();
delay("Your name is: " + playerName, 60L);
delay("Welcome to this Bakery!", 40L);
delay("This Bakery has been without an owner for so long...",40L);
delay("Most of it's recipies have been lost.", 40L);
delay("It's up to you to collect all of the lost recipies!", 40L);
delay("These are the ingredients provided: ", 60L);
delay("Base flavors: " + Arrays.toString(f), 60L);
delay("Toppings: " + Arrays.toString(t), 60L);
while (achievements != 16){
System.out.println("Pick a flavor");
String flavor = sc.nextLine();
if (flavor.equalsIgnoreCase("quit")){
delay("Thanks for playing!", 40L);
System.exit(0);
}
String cuFlavor = flavor.toLowerCase();
boolean oo = false;
while (oo){
if(Arrays.asList(f).contains(cuFlavor)){
oo = true;
}
}
if (Arrays.asList(f).contains(cuFlavor) == false){
delay("Not an option, please pick again.", 40L);
flavor = sc.nextLine();
}
System.out.println("Pick a topping");
String topping = sc.nextLine();
if (topping.equalsIgnoreCase("quit")){
delay("Thanks for playing!", 40L);
System.exit(0);
}
String cuTopping = topping.toLowerCase();
boolean tt = false;
while (tt==false){
if(Arrays.asList(t).contains(cuTopping) == true){
tt = true;
}
}
if (Arrays.asList(t).contains(cuTopping) == false){
delay("Not an option, please pick again.", 40L);
topping = sc.nextLine();
}
String cake = cuFlavor+cuTopping;
boolean bb = false;
while (bb == false){
if(foundCakes.contains(cake)){
delay("Previously found recipe!", 40L);
delay(getRandomResponse(), 40L);
bb = true;
}
}
boolean nc = true;
while(nc == true){
if(foundCakes.contains(cake) == false){
delay("You found a new cake!", 40L);
delay("Unlocked: "+cake, 40L);
foundCakes.add(cake);
achievements++;
delay("Number of recipes found: " + achievements, 40L);
nc = false;
}
}
}
System.exit(0);
}
public int getAchievements(){
return achievements;
}
private static String getRandomResponse()
{
final int NUMBER_OF_RESPONSES = 4;
double r = Math.random();
int whichResponse = (int)(r * NUMBER_OF_RESPONSES);
String response = "";
if (whichResponse == 0)
{
response = "Don't worry! Still delicious.";
}
else if (whichResponse == 1)
{
response = "What a classic cake!";
}
else if (whichResponse == 2)
{
response = "Yummy :)";
}
else if (whichResponse == 3)
{
response = "Smells nice!";
}
return response;
}
public String toString(){
return "Flavors: "+Arrays.toString(f)+" Topping: "+Arrays.toString(t);
}
public static void delay(String s, long delay) throws InterruptedException {
for ( int i= 0; i < s.length(); i++) {
// for loop delays individual String characters
System.out.print(s.charAt(i));
Thread.sleep(delay); //time is in milliseconds
}
System.out.println(""); // this is the space in between lines
}
}
Take a look at your while loops. First:
boolean oo = false;
while (oo){
if (Arrays.asList(f).contains(cuFlavor)) {
oo = true;
}
}
This loop is never entered since oo == false.
Next:
boolean tt = false;
while (tt == false) {
if (Arrays.asList(t).contains(cuTopping) == true) {
tt = true;
}
}
This loop does execute, but what happens if t does not contain cuTopping? In that case, tt never get sets to true and the loop goes on forever.
The next two loops have the same issue.
You need to ensure the loops will end at some point. Example:
while (tt == false) {
if (Arrays.asList(t).contains(cuTopping) == true) {
tt = true;
}
else {
// Do something to change cuTopping
System.out.println("Pick a topping");
cuTopping = sc.nextLine();
// etc....
}
}
You can combine the loops with the gathering of the input:
String cuTopping = null;
do {
if (cuTopping != null) { // Only true after first iteration
System.out.println("That topping is not in the list!");
}
System.out.println("Pick a topping");
cuTopping = sc.nextLine().toLowerCase();
if (cuTopping.equalsIgnoreCase("quit")) {
delay("Thanks for playing!", 40L);
System.exit(0);
}
} while (!Arrays.asList(t).contains(cuTopping));
I've just started learning java since last week. I'm using book called 'head first java' and i'm struggling with solving problems about ArrayList. Error says "The method setLocationCells(ArrayList) in the type DotCom is not applicable for the
arguments (int[])" and I haven't found the solution :( help me..!
enter image description here
This looks like a Locate & Conquer type game similar to the game named Battleship with the exception that this game is a single player game played with a single hidden ship in a single horizontal row of columnar characters. Rather simplistic but kind of fun to play I suppose. The hard part is to locate the hidden ship but once you've located it, conquering (sinking) it becomes relatively easy. I'm sure this isn't the games' intent since it is after all named "The Dot Com Game" but the analogy could be possibly helpful.
There are several issues with your code but there are two major ones that just can not be there for the game to work:
Issue #1: The call to the DotCom.setLocationCells() method:
The initial problem is located within the DotComGame class on code line 13 (as the Exception indicates) where the call is made to the DotCom.setLocationCells() method. As already mentioned in comments the wrong parameter type is passed to this method. You can not pass an int[] Array to the setLocationCell() method when this method contains a parameter signature that stipulates it requires an ArrayList object. The best solution in my opinion would be to satisfy the setLocationCells() method parameter requirement...supply an ArrayList to this method.
The reason I say this is because all methods within the DotCom class work with an established ArrayList and one of the tasks of one of these methods (the checkYourself() method) actually removes elements from the ArrayList which is easy to do from a collection but very cumbersome to do the same from an Array.
To fix this problem you will need to change the data type for the locations variable located within the DotComGame class. Instead of using:
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
you should have:
ArrayList<Integer> locations = new ArrayList<>(
Arrays.asList(random, randomNum + 1, randomNum + 2));
or you could do it this way:
ArrayList<Integer> locations = new ArrayList<>();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
There are other ways but these will do for now. Now, when the call to the setLocationCells() method is made you ahouldn't get an exception this issue should now be resolved.
Issue #2: The call to the DotCom.checkYourself() method:
Again, this particular issue is located within the DotComGame class on code line 18 where the call is made to the DotCom.checkYourself() method. Yet another parameter data type mismatch. You are trying to pass a variable of type String (named guess) to this method whereas its signature stipulates that it requires an integer (int) value. That again is a no go.
To fix this problem you will need to convert the string numerical value held by the guess variable to an Integer (int) value. So instead of having this:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
String result = theDotCom.checkYourself(guess);
// ... The rest of your while loop code ...
}
you should have something like:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
/* Validate. Ensure guess holds a string representation
of a Integer numerical value. */
if (!guess.matches("\\d+")) {
System.err.println("Invalid Value (" + guess
+ ") Supplied! Try again...");
continue;
}
int guessNum = Integer.parseInt(guess);
String result = theDotCom.checkYourself(guessNum);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println(numOfGuesses + " guesses!");
}
else if (result.equals("hit")) {
// Do Something If You Like
System.out.println("HIT!");
}
else {
System.out.println("Missed!");
}
}
Below is a game named Simple Battleship which I based off of your code images (please don't use images for code anymore - I hate using online OCR's ;)
BattleshipGame.java - The application start class:
import java.awt.Toolkit;
public class BattleshipGame {
public static int gameLineLength = 10;
public static void main(String[] args) {
GameHelper helper = new GameHelper();
Battleship theDotCom = new Battleship();
int score = 0; // For keeping an overall score
// Display About the game...
System.out.println("Simple Battleship Game");
System.out.println("======================");
System.out.println("In this game you will be displayed a line of dashes.");
System.out.println("Each dash has the potential to hide a section of a");
System.out.println("hidden Battleship. The size of this ship is randomly");
System.out.println("chosen by the game engine and can be from 1 to 5 sections");
System.out.println("(characters) in length. The score for each battle is based");
System.out.println("on the length of the game line that will be displayed to");
System.out.println("you (default is a minimum of 10 charaters). You now have");
System.out.println("the option to supply the game line length you want to play");
System.out.println("with. If you want to use the default then just hit ENTER:");
System.out.println();
// Get the desire game line length
String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
if (!length.isEmpty()) {
gameLineLength = Integer.parseInt(length);
}
System.out.println();
// Loop to allow for continuous play...
boolean alwaysReplay = true;
while (alwaysReplay) {
int numOfGuesses = 0;
/* Create a random ship size to hide within the line.
It could be a size from 1 to 5 characters in length. */
int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
int[] locations = new int[shipSize];
for (int i = 0; i < locations.length; i++) {
locations[i] = randomNum + i;
}
System.out.println("Destroy the " + shipSize + " character ship hidden in the");
System.out.println("displayed line below:");
System.out.println();
String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
theDotCom.setLocationCells(locations);
// Play current round...
boolean isAlive = true;
while (isAlive == true) {
System.out.println(gameLine);
String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
+ " (0 to quit): --> ", "Integer", 1, gameLineLength);
int idx = Integer.parseInt(guess);
if (idx == 0) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
alwaysReplay = false;
break;
}
idx = idx - 1;
String result = theDotCom.checkYourself(idx);
numOfGuesses++;
System.out.println(result);
if (result.equalsIgnoreCase("kill")) {
Toolkit.getDefaultToolkit().beep();
isAlive = false;
/* Tally the score dependent upon the gameLineLength... */
if (gameLineLength <= 10) { score += 5; }
else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
else { score += 25; }
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
System.out.println(gameLine);
System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
}
else if (result.equalsIgnoreCase("hit")) {
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
}
if (result.equalsIgnoreCase("miss")) {
score -= 1;
}
System.out.println();
}
// Play Again? [but only if 'alwaysReplay' holds true]
if (alwaysReplay) {
String res = helper.getAnything("<< Press ENTER to play again >>\n"
+ "<< or enter 'q' to quit >>");
if (res.equalsIgnoreCase("q")) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
break;
}
System.out.println();
}
}
}
}
GameHelper.java - The GameHelper class:
import java.util.Scanner;
public class GameHelper {
private final Scanner in = new Scanner(System.in);
public String getUserInput(String prompt, String responseType, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (response.isEmpty() && allowNothing) {
return "";
}
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getAnything(String prompt) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
return in.nextLine().trim();
}
}
Battleship.java - The Battleship class:
import java.util.ArrayList;
public class Battleship {
private ArrayList<Integer> locationCells;
public void setLocationCells(java.util.ArrayList<Integer> loc) {
locationCells = loc;
}
// Overload Method (Java8+)
public void setLocationCells(int[] loc) {
locationCells = java.util.stream.IntStream.of(loc)
.boxed()
.collect(java.util.stream.Collectors
.toCollection(java.util.ArrayList::new));
}
/*
// Overload Method (Before Java8)
public void setLocationCells(int[] loc) {
// Clear the ArrayList in case it was previously loaded.
locationCells.clear();
// Fill the ArrayList with integer elements from the loc int[] Array
for (int i = 0; i < loc.length; i++) {
locationCells.add(loc[i]);
}
}
*/
/**
* Completely removes one supplied Integer value from all elements
* within the supplied Integer Array if it exist.<br><br>
*
* <b>Example Usage:</b><pre>
*
* {#code int[] a = {103, 104, 100, 10023, 10, 140, 2065};
* a = removeFromArray(a, 104);
* System.out.println(Arrays.toString(a);
*
* // Output will be: [103, 100, 10023, 10, 140, 2065]}</pre>
*
* #param srcArray (Integer Array) The Integer Array to remove elemental
* Integers from.<br>
*
* #param intToDelete (int) The Integer to remove from elements within the
* supplied Integer Array.<br>
*
* #return A Integer Array with the desired elemental Integers removed.
*/
public static int[] removeFromArray(int[] srcArray, int intToDelete) {
int[] arr = {};
int cnt = 0;
boolean deleteIt = false;
for (int i = 0; i < srcArray.length; i++) {
if (srcArray[i] != intToDelete) {
arr[cnt] = srcArray[i];
cnt++;
}
}
return arr;
}
public String checkYourself(int userInput) {
String result = "MISS";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "KILL";
}
else {
result = "HIT";
}
}
return result;
}
}
So I have this method here
while(oMenu == 1 || oMenu == 2){
oMeny = Kbd.readInt("\nClick 1 to make an account\nClick 2 to login\nClick 3 to exit the program");
if(oMeny == 1){
for(int i = 0; Account[i] != null; i++){
if(Account[i] == null){
pos = i;
}
}
Account[pos] = new Account();
}
if(oMeny == 2){
String s = Kbd.readString("Input your accountnumber: ");
for(int i = 0; Account[i] != null; i++){
if(Account[i] != null && s.equals(Account[i].getAccountNumber())){
System.out.println("Welcome!");
// Here is rest of my code , the "inner" menu that works menyMetod(iMeny,mMeny);
}
else{
System.out.println("There are no accounts with that given accountnumber!");
}
}
}
}
}
I want to understand why if I access the oMeny == 1 and make 2 accounts Why I can't seem to access the first one I make but rather the latest one? It seems that somehow my array "overwrites" the first empty position. Basically I want to find the first empty position in my array, so in the first case it's always index 0 and then the next time I make an account again, it should be Index 1 logically.
EDIT : Heres my code for the Account class
public class Account{
private int money, transactions;
private String AccountNumber;
public Account(){
money = Kbd.readInt("\nHow much money do you want to put in?");
AccountNumber = Kbd.readString("\nWhat account number do you want?");
}
The error is here:
for (int i = 0; accounts[i] != null; i++) {
if (accounts[i] == null)
The for loop repeats as long i points to a non-null entry. Therefore the if-condition is never true.
This becomes quickly obvious when you run the program line by line in a debugger.
Next time please provide a complete code example that can be compiled. Your code is full of error, It took me a lot of time to fix it before I was able to execute it.
Corrected code:
import java.util.Scanner;
class Main
{
static Scanner kbd = new Scanner(System.in);
static Account[] accounts = new Account[100];
static class Account
{
//public int money;
public String accountNumber;
public Account()
{
//System.out.println("\nHow much money do you want to put in?");
//money = Kbd.nextInt();
System.out.println("\nWhat account number do you want?");
accountNumber = kbd.next();
}
}
public static void main(String[] args)
{
int oMenu = 1;
int pos = 0;
while (oMenu == 1 || oMenu == 2)
{
System.out.println("\nClick 1 to make an account\nClick 2 to login\nClick 3 to exit the program");
oMenu = kbd.nextInt();
if (oMenu == 1)
{
for (int i = 0; i<accounts.length; i++)
{
if (accounts[i] == null)
{
accounts[i] = new Account();
break;
}
}
}
if (oMenu == 2)
{
System.out.println("Input your accountnumber: ");
String s = kbd.next();
Account found=null;
for (int i = 0; i<accounts.length; i++)
{
if (accounts[i] != null && s.equals(accounts[i].accountNumber))
{
found=accounts[i];
}
}
if (found!=null)
{
System.out.println("Welcome! nr. "+found.accountNumber);
}
else
{
System.out.println("There are no accounts with that given accountnumber!");
}
}
}
}
}
Notice how I also fixed the second for-loop.
You did not show the declaration or initialization of pos, so I think it is not working how you expect because you do not go into the for loop where Account[i] is null to set pos. Try this
if(oMenu == 1){
int pos = 0;
while (Account[pos] != null && pos < Account.length)
pos++;
if (pos < Account.length)
Account[pos] = new Account();
else{
//expand array and add account or throw error
}
}
I have downloaded a java file needed for a coursework at college. However I find it impossible to run it. Eclipse won't give me the chance to even run it (only ant build), and if I use netbeans I get this exception :
Exception in thread "main"
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Uncompilable source code - class Hangman is public, should be declared in a file named Hangman.java
at Hangman. < clinit > (hangman(Case Conflict).java: 20)
Java Result: 1
If someone is kind enough to read through the code, I really do not know what to do next. I figure there has to be something wrong with the main class. Thanks!
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
class Hangman {
Scanner userInput;
private Set < Character > wrongGuesses;
private String[] answers = {
"leverets", "hatchlings", "puppies",
"kittens", "pullets", "goslings"
};
private String answer;
private String guessed;
private int maxTurns;
private int currentTurns;
private boolean inProgress;
private char nextGuess;
private boolean gameWin;
public Hangman() {
userInput = new Scanner(System.in);
wrongGuesses = new HashSet < Character > ();
inProgress = false;
gameWin = false;
maxTurns = 14;
currentTurns = 0;
// set answer somehow
answer = answers[0];
// set guessed to the correct number of dashes
StringBuilder sb = new StringBuilder();
for (int i = 0; i < answer.length(); i++) {
sb.append('-');
}
guessed = sb.toString();
}
/* start a new game */
public void startGame() {
inProgress = true;
startGameLoop();
}
/* the game loop. this method is the heart of the game */
private void startGameLoop() {
printInstructions();
while (inProgress) {
printStatus();
acceptGuess();
checkStatus();
}
printWinOrLose();
}
private void printInstructions() {
System.out
.println("Guess the word one letter at a time until you win or run out of turns. Good luck!");
}
private void printWinOrLose() {
if (gameWin) {
System.out.println("You win! The answer was " + answer);
} else {
System.out.println("You lose.");
}
}
private void printStatus() {
System.out.println("Guesses left: " + (maxTurns - currentTurns));
System.out.println("Current status: " + guessed);
System.out.println("Wrong guesses: " + getWrongAnswers());
}
/* get the next character from the player */
private void acceptGuess() {
System.out.println("Next guess: ");
String temp = userInput.next();
nextGuess = temp.charAt(0);
}
/* check what state the game is in */
private void checkStatus() {
// if already guessed, say already guessed.
if (wrongGuesses.contains(nextGuess)) {
System.out.println("You already guessed that!");
return;
}
// if guess is not in answer, update number of turns played and add
// guess to wrong guesses
// otherwise update the guessed variable
if (answer.indexOf(nextGuess) < 0) {
++currentTurns;
wrongGuesses.add(nextGuess);
} else {
updateGuessStatus();
}
// check to see if the player has won or lost
if (answer.equals(guessed)) {
gameWin = true;
inProgress = false;
}
if (currentTurns == maxTurns) {
inProgress = false;
}
}
/* update the guessed variable when there is a correct guess made */
private void updateGuessStatus() {
// replace - with nextGuess where appropriate
int index = answer.indexOf(nextGuess);
int lastIndex = answer.lastIndexOf(nextGuess);
StringBuilder sb = new StringBuilder(guessed);
if (index != lastIndex) { // more than one instance of the guess in the
// answer
// swap out in a loop
while (index != -1) {
sb.setCharAt(index, nextGuess);
int i = answer.indexOf(nextGuess, (index + 1));
index = i;
}
} else { // letter only appears once
// swap out just that one
sb.setCharAt(index, nextGuess);
}
guessed = sb.toString();
}
/* build a text representation of all the incorrect guesses */
private String getWrongAnswers() {
if (wrongGuesses.size() > 0) {
StringBuilder sb = new StringBuilder();
sb.append('(');
for (Character c: wrongGuesses) {
sb.append(c + ",");
}
sb.deleteCharAt(sb.length() - 1); // delete trailing comma
sb.append(')');
return sb.toString();
} else {
return "<none>";
}
}
public static void main(String[] args) {
Hangman h = new Hangman();
h.startGame();
}
}
The exception says everything you need to know. Rename the class FILE to Hangman.java.
Caused by: java.lang.RuntimeException: Uncompilable source code - class Hangman is public, should be declared in a file named Hangman.java
You should save your downloaded file in Hangman.java and not hangman.java (see it needs 'H' in caps same as your class name).
Change the class to public class Hangman. It allows outside methods to access it.
EDIT: I downloaded the file, changing the class to public worked. I also found an issue in the code itself, the word is always "Leverets".
To change this, edit the getAnswer() method and change it to
private int getAnswer() {
int i = (int) (Math.random() * 6) + 0;
return i;
}
I need to do a Credit card number validation.
When I googled this I found the org.apache.commons.validator.CreditCardValidator. But seems like it is not working correctly.
When I pass a non-digit character also it porvides true.
Code for Apache CreditCardValidator:
String ccNumber = "378282246310005";
CreditCardValidator creditCardValidator = new CreditCardValidator();
if(!creditCardValidator.isValid(ccNumber)) throw new Exception("Credit Card Number is not a valid one!");
Then, I wrote following methods to validate credit card numbers based on the card type and the card number (using the luhn's algorithm).
CardType validator (null if an invalid card type)
public String getCCType(String ccNumber){
String visaRegex = "^4[0-9]{12}(?:[0-9]{3})?$";
String masterRegex = "^5[1-5][0-9]{14}$";
String amexRegex = "^3[47][0-9]{13}$";
String dinersClubrRegex = "^3(?:0[0-5]|[68][0-9])[0-9]{11}$";
String discoverRegex = "^6(?:011|5[0-9]{2})[0-9]{12}$";
String jcbRegex = "^(?:2131|1800|35\\d{3})\\d{11}$";
String commonRegex = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$";
try {
ccNumber = ccNumber.replaceAll("\\D", "");
return (ccNumber.matches(visaRegex) ? "VISA" : ccNumber.matches(masterRegex) ? "MASTER" :ccNumber.matches(amexRegex) ? "AMEX" :ccNumber.matches(dinersClubrRegex) ? "DINER" :ccNumber.matches(discoverRegex) ? "DISCOVER" :ccNumber.matches(jcbRegex) ? "JCB":null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
CardNumber validator using Luhn's algorithem.
public boolean isValidCardNumber(String ccNumber){
try {
ccNumber = ccNumber.replaceAll("\\D", "");
char[] ccNumberArry = ccNumber.toCharArray();
int checkSum = 0;
for(int i = ccNumberArry.length - 1; i >= 0; i--){
char ccDigit = ccNumberArry[i];
if((ccNumberArry.length - i) % 2 == 0){
int doubleddDigit = Character.getNumericValue(ccDigit) * 2;
checkSum += (doubleddDigit % 9 == 0 && doubleddDigit != 0) ? 9 : doubleddDigit % 9;
}else{
checkSum += Character.getNumericValue(ccDigit);
}
}
return (checkSum != 0 && checkSum % 10 == 0);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
I want to know,
Is there any other thrid party class to validate the credit cards
other than the org.apache one?
Is there any issue with the my code?
(I tested it for several times. So far so good. I just want to know
if you could spot something that I didn't.)
References :
How do you detect Credit card type based on number?
I did this a long time ago, Sorry Code is in C. Easily Convertible. Hope this will help you.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int CardNoChecker(unsigned long long int Number)
{
int dijts=0;
int Ans=0;
{
unsigned long long int k=1;
while(Number%k!=Number)
{
dijts=dijts+1;
k=k*10;
}
}
{
int i=1;
int Product=0;
int Sum=0;
for(i=dijts;i>=1;i--)
{
if(i%2==0)
{
if((Number%10)*2<10)
Product = Product + ( Number % 10 ) * 2 ;
else
{
int No=(Number%10)*2;
Product = Product + No/10;
Product = Product + No%10;
}
}
else
{
Sum = Sum + ( Number % 10 ) ;
}
Number=Number /10;
}
Ans = Sum + Product ;
}
if(Ans%10==0)
return (1);
else
return (0);
}
int main()
{
unsigned long long int CardNO;
int valid=0;
while(!valid)
{
int CnV=0;
int VC=0;
int AE=0;
int MC=0;
printf("Enter Card NO : ");
scanf("%llu",&CardNO);
if(CardNO/1000000000000==4 || CardNO/1000000000000000==4)
{
VC=1;
}
else if(CardNO/10000000000000==34 ||CardNO/10000000000000==37)
{
AE=1;
}
else if(CardNO/100000000000000==51 || CardNO/100000000000000==52 || CardNO/100000000000000==53 || CardNO/100000000000000==54 || CardNO/100000000000000==55)
{
MC=1;
}
CnV=CardNoChecker(CardNO);
if(CnV && MC )
printf("This is a Valid Master Card\n\n");
else if(CnV && VC )
printf("This is a Valid Visa Card\n\n");
else if(CnV && AE )
printf("This is a Valid American Express Card\n\n");
else
printf("Card is Not Valid'\n\n");
}
return (0);
}
Have a look to Luhn algorithm
https://en.wikipedia.org/wiki/Luhn_algorithm
public static void main(String[] args) {
boolean isValid = checkCC("4561 2612 1234 5467");
System.out.println(isValid);
}
private static boolean checkCC(String input) {
String purportedCC = input.replaceAll(" ", "");
int sum = 0;
for (int i = 0; i < purportedCC.length(); i++) {
int cardNum = Integer.parseInt(
Character.toString(purportedCC.charAt(i)));
if ((purportedCC.length() - i) % 2 == 0) {
cardNum = cardNum * 2;
if (cardNum > 9) {
cardNum = cardNum - 9;
}
}
sum += cardNum;
}
return sum % 10 == 0;
}
You can find custom implantation of credit card validator here which is doing both credit card number validation plus credit card type detection,
http://www.esupu.com/credit-card-validator-java/