Why wont my Strings compare? - java

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

Related

Java Shut the Box

Im writing a program similar to a game called shut the box. The game asks the player to roll 2 die, and then the player chooses to cover both numbers individually (in the boolean array), or the total of the two.
I'm having difficulty returning two values of the int method roll() which is supposed to roll two die.
Heres my code for the main class:
public class clacker {
private int play;
private int die1;
private int die2;
private boolean[] table;
private final int high = 6;
private final int low = 1;
private int range;
public clacker()
{
range = high-low+1;
table = new boolean[13];
play = 0;
}
public void roll()
{
die1 = (int)(Math.random()*range+low);
die2 = (int)(Math.random()*range+low);
}
public void value(char ch)
{
if(ch == 'i' || ch == 'I')
{
table[die1] = true;
table[die2] = true;
displayBoard();
}
else if(ch == 'T' || ch == 't')
{
table[die1+die2] = true;
displayBoard();
}
else
{
roll();
}
}
public void displayBoard()
{
for(int i = 1; i<table.length; i++)
{
if(table[i] == false)
{
System.out.print(" " + i + " ");
}
else
{
System.out.print(" / ");
}
}
}
}
and for the test class:
public class clackerTest {
public static void main(String[] args) {
clacker oo = new clacker();
EasyReader kboard = new EasyReader();
System.out.println("Press anything to roll the dice. ");
char roll= kboard.readChar();
int dice1 = oo.roll();
int dice2 = oo.roll();
System.out.println("You rolled " + dice1 + " and a " + dice2 + "!");
System.out.println("Cover Individual or Total: (enter i or t)");
char roll2 = kboard.readChar();
}
}
Why don't you just roll() twice? Modify roll() to return one int.
public int roll() {
return (int)(Math.random()*range+low);
}
And now, from within clackerTest (java conventions dictates you name this ClackerTest):
int dice1 = oo.roll();
int dice2 = oo.roll();

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.

Unable to solve this, updating arrays in java

I am about to complete a text based java board game (Very basic). And I am stuck on this last thing -
Basically what happens is when a user has types 'roll' to roll the virtual die. Then depending on the results an array gets updated to change the location of 'o' (which makes it look like there counter has been moved). I have figured out how to make this for the first roll.
But what I cannot figure out is how to make the second roll and first roll add up (and so on with third and fourth roll).
(example -
Roll 1: Player rolls the die - gets a 3 - moves to 3rd position on the board (solved)
Roll 2: The game remembers that the last roll was a 3 - player rolls a 4 - updates the board and moves the counter to number 7)
Here is a snippet of the relevant code:
public void play(String p1Name2, String p2Name2){
Scanner user_input = new Scanner(System.in);
Random rn = new Random();
String p1Roll = null,p2Roll;
int[] p1r = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int b= 0,c= 0,d = 0,e = 0,g = 0;
while(array1[10] != 'o'){
c++;
if(b==0) {
int i =1;
System.out.println("Player 1, type roll to roll the die. ");
p1Roll = user_input.next();
if(p1Roll.equalsIgnoreCase("roll")){
p1r[c] = rn.nextInt(6);
p1r[c] += 1;
System.out.println("You rolled a: " + p1r[c]);
for(int f = 0; f< 10; f++ ){
if(array1[f] == 'o'){
array1[f] = 'x';
array1[p1r[c]] = 'o';
if(i ==1){
this.board();
i = 0;
}
}
}
}
if(b==1) {
}
}
}
}
and
public void board(){
System.out.println(" 1 2 3 4 (5) 6 7 8 9 10 11");
System.out.println("Player 1: " + array1[0]+ " " + array1[1] + " " + array1[2]+ " " + array1[3] + " " + array1[4]+ " " + array1[5] + " " + array1[6]+ " " + array1[7] + " " + array1[8]+ " " + array1[9] + " " + array1[10]);
System.out.println("Player 2: " + array2[0]+ " " + array2[1] + " " + array2[2]+ " " + array2[3] + " " + array2[4]+ " " + array2[5] + " " + array2[6]+ " " + array2[7] + " " + array2[8]+ " " + array2[9] + " " + array2[10]);
}
Finally, here is the console output:
Player 1, type roll to roll the die.
roll
You rolled a: 4
1 2 3 4 (5) 6 7 8 9 10 11
Player 1: x x x x o x x x x x x
Player 2: o x x x x x x x x x x
Player 1, type roll to roll the die.
roll
You rolled a: 4
1 2 3 4 (5) 6 7 8 9 10 11
Player 1: x x x x o x x x x x x
Player 2: o x x x x x x x x x x
Player 1, type roll to roll the die.
roll
You rolled a: 2
1 2 3 4 (5) 6 7 8 9 10 11
Player 1: x x o x x x x x x x x
Player 2: o x x x x x x x x x x
Player 1, type roll to roll the die.
You could change the code as follows:
public void play(String p1Name2, String p2Name2){
Scanner user_input = new Scanner(System.in);
Random rn = new Random();
String p1Roll = null,p2Roll;
int[] p1r = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int b= 0,c= 0,d = 0,e = 0,g = 0;
while(array1[10] != 'o'){
c++;
if(b==0) {
int i =1;
System.out.println("Player 1, type roll to roll the die. ");
p1Roll = user_input.next();
if(p1Roll.equalsIgnoreCase("roll")){
p1r[c] = rn.nextInt(6);
p1r[c] += 1;
System.out.println("You rolled a: " + p1r[c]);
for(int f = 0; f< 10; f++ ){
if(array1[f] == 'o'){
array1[f] = 'x';
/** Update Current Position **/
array1[p1r[f] + p1r[c]] = 'o';
if(i == 1){
this.board();
i = 0;
}
break;
}
}
}
}
}
}
However, note that you're currently risking to get ArrayIndexOutOfBoundException in array[p1r[c]], as well as in the updated version. Hence, I would suggest you to address that, e.g.using moduled accesses array[(p1r[c%p1r.length]%array.length)]. It depends on the game behaviour you would like to have in such situations.
Hope it helps!
You asked me how it would look like in objects. it would look like this:
The group holds all the players.
The players have a board.
The board tracks each players location.
import java.util.*;
import java.lang.*;
import java.io.*;
class Game
{
public static void main (String[] args) throws java.lang.Exception
{
Group group = new Group();
group.createPlayer("Michael");
group.createPlayer("Jeff");
group.createPlayer("Fred");
group.renderBoard();
int round = 1;
while(true) {
System.out.println("Game round "+round);
round++;
group.getInputs();
group.renderBoard();
if(group.isGameFinished()) {
Player winner = group.getWinner();
System.out.println("Player "+winner.getName() + " is the winner! Congratulations");
break;
}
}
}
}
class Group {
private ArrayList<Player> group;
public Group() {
this.group = new ArrayList<Player>();
}
public void createPlayer(String name) {
this.group.add(new Player(name));
}
public void renderBoard() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player current = it.next();
current.renderBoard();
}
}
public void getInputs() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player currentMove = it.next();
currentMove.getDiceRoll();
}
}
public boolean isGameFinished() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player currentMove = it.next();
if(currentMove.isFinished()) {
return true;
}
}
return false;
}
public Player getWinner() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player currentMove = it.next();
if(currentMove.isFinished()) {
return currentMove;
}
}
return new Player("Nobody");
}
}
class Player {
private Scanner user_input;
private Random rn;
private String name;
private Board board;
public Player(String name) {
this.name = name;
this.user_input = new Scanner(System.in);
this.rn = new Random();
this.board = new Board(11);
}
public void getDiceRoll() {
System.out.println("Player "+this.name+", type roll to roll the die. ");
String input = user_input.next();
if(input.equalsIgnoreCase("roll")) {
int dieRoll = rn.nextInt(6);
System.out.println("You rolled a "+dieRoll+"!");
this.board.updateLocation(dieRoll);
}
}
public String getName() {
return this.name;
}
public boolean isFinished() {
return this.board.isFinished();
}
public void renderBoard() {
System.out.println(this.name +" > "+this.board.renderBoard());
}
}
class Board {
private int size;
private int location;
public Board(int size) {
this.size = size;
this.location = size;
}
public void reset() {
this.location = this.size;
}
public boolean isFinished() {
return this.location <= 0;
}
public void updateLocation(int amount) {
this.location -= amount;
if(this.location < 0) {
this.location = 0;
}
}
public String renderBoard() {
StringBuilder builder = new StringBuilder();
for(int c=0;c<=this.size;c++) {
if(c == this.location) {
builder.append('o');
}
else {
builder.append('x');
}
builder.append(' ');
}
return builder.toString();
}
}

Array not printing properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}

Validating against duplicate user entries when using sets

I am currently studying Java and have being using normal arrays so far. Next semester we will be using data structures like ArrayList etc, but i decided to read ahead. I have read that for storing data that can not be a duplicate, Sets were the data structure of choice, but in the code below the user can still enter a duplicate entry? Can any body explain the process to me and perhaps a solution to my problem?
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 0;
private static final int MAX_NUMBER_POSSIBLE = 25;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Pick " + INPUT_SIZE + " numbers from "
+ MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ".");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("You win :) !");
} else {
System.out.println("Sorry you failed :( !");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nRandom numbers where : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChoosen = input.nextInt();
if (numberChoosen < MIN_NUMBER_POSSIBLE
|| numberChoosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in "
+ MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE
+ " range.");
} else {
userNumbers.add(numberChoosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been called.");
}
}
Set#add(Object) returns true when the object was added successfully and false otherwise. It will not throw an exception, so you need to add a conditional to check whether the operation was successful:
if (userNumbers.add(numberChoosen)) {
System.out.println("Number added successfully");
} else {
System.out.println("Duplicate number detected");
}
Sets do not prohibit entering a unique value more than once. It is on you to check preconditions, see e.g Set.add.
So instead of just calling:
userNumbers.add(numberChoosen);
try
if (!userNumbers.contains(numberChoosen)) {
userNumbers.add(numberChoosen);
} else {
// do stuff...
}

Categories

Resources