I'm trying to make a basic "Deal or No Deal" game in Java. I'm running into issues with adding and removing to my multidimensional arraylist.
The issue occurs in line 7 of shuffleBoxes() and line 9 of playerBox().
package Deal;
import java.util.*;
import java.io.*;
import javax.swing.*;
public class sample {
public static ArrayList <ArrayList<Integer>> boxes = new ArrayList<ArrayList<Integer>>(22);
public static void main (String [] args) throws IOException {
playerBox();
dealerOffer();
}
public static void shuffleBoxes() {
int [] prizes = {1,2,3,4,5,6,10,50,100,250,500,750,1000,3000,10000,15000,20000,35000,50000,75000,100000,250000};
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).add(i+1);
}
for (int j = 0; j < boxes.size(); j++) {
boxes.get(j).get(1).add(prizes[j]);
}
Collections.shuffle(boxes);
}
public static int playerBox () {
String[] boxChoice = {"1", "2", "3", "4", "5", "6", "7", "8", "9" ,"10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22"};
String input = (String)JOptionPane.showInputDialog(null, "Choose a box...", "Choose carefully",
JOptionPane.QUESTION_MESSAGE, null, boxChoice, boxChoice[0]);
int chosenBox = Integer.parseInt(input);
for (int i = 0; i < boxes.size(); i++) {
if (chosenBox == boxes.get(i).get(0))
boxes.get(i).get(0).remove(chosenBox);
}
return chosenBox;
}
public static void dealerOffer() {
int average;
int sum = 0;
for (int i = 0; i < boxes.size(); i++) {
sum = sum + (boxes.get(i).get(1));
}
average = sum / boxes.size();
}
}
You create
ArrayList <ArrayList<Integer>> boxes = new ArrayList<ArrayList<Integer>>(22);
but this does not put anything into the ArrayList. I don't see any references to boxes.add(...) in your code, so any attempt to use boxes.get() will throw an exception.
It is not at all clear why you think you need a List<List<Integer>>. A multidimensional list is generally code smell. In 99% of cases a different data structure using custom objects will be more appropriate.
Related
I am trying to create mutliple methods which all use data from the same array. The method createDeck works fine. But for the other two methods, they just return null. Is there a way to fix this?
class Deck
{
private static String[] suit = {"Spades", "Diamonds", "Clubs", "Hearts"};
private static String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen",
"King", "Ace"};
private static String[] deck = new String[52];
// create deck
static void createDeck()
{
for (int i = 0; i < deck.length; i++)
{
deck[i] = rank[i % 13] + " of " + suit[i / 13];
System.out.println(deck[i]);
}
}
// shuffle deck
static void shuffleDeck()
{
// shuffle the deck
for (int i = 0; i < deck.length; i++)
{
int index = (int) (Math.random() * deck.length);
String temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
// print the shuffled deck
for (String u : deck)
{
System.out.println(u);
}
}
static void findTop()
{
System.out.println(deck[0]);
}
}
One way to solve this is to directly fill the array using a static initalizer which gets called automatically.
Just add this code block after the decalration of the array at the beginning of the class
private static String[] deck = new String[52];
static {
for (int i = 0; i < deck.length; i++)
{
deck[i] = rank[i % 13] + " of " + suit[i / 13];
System.out.println(deck[i]);
}
}
And of course remove the method createDeck since it is no longer needed. The following code will now be executed correctly and printing values from the array
public static void main(String[] args) {
Deck.findTop();
Deck.shuffleDeck();
}
See this question for more info on static initializer
If it is used in your object, you can put the Array inside the constructor of an object.
public class Deck {
String[] deck;
public Deck(){
this.deck = new String[52];
}
}
I have a problem in my Java program Black Jack. I can't seem to work out my "this.cards[o++]" as it always goes into ArrayIndexOutOfBoundException. But if I change it into "this.cards[j] OR this.cards[i]" it doesn't get an error but I know its wrong.
Here's the errors for:
**this.cards[o++]**
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
at CardDeck.<init>(CardDeck.java:18)
at BlackJoker.main(BlackJoker.java:17)
**this.cards[j]**
null
Kc
Qc
8c
null
null
**this.cards[i]**
null
Ac
Ah
null
null
Ad
Here's my code:
import java.util.*;
public class CardDeck
{
private String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K", "A" };
private char[] suits = {'s','h','d','c'};
private Card[] cards = new Card[13];
private int currentCard;
CardDeck()
{
Card newCard;
int o = 0;
for(int i=0; i<this.suits.length; i++)
{
for(int j=0; j<this.ranks.length; j++)
{
this.cards[o++] = new Card(this.ranks[j], this.suits[i]);
}
}
this.shuffle();
}
public void testing() //just for testing
{
System.out.println(this.suits[0]);
}
public Card drawNextCard()
{
return cards[currentCard++];
}
private void shuffle()
{
Card[] tmp = new Card[13];
for (int i = 0; i < cards.length; i++)
{
int index = (int)(Math.random() * (cards.length));
tmp[index] = cards[i];
cards[i] = cards[index];
cards[index] = tmp[i];
}
}
}
public class BlackJoker
{
public static void main(String[] args)
{
CardDeck cardDeck = new CardDeck();
//cardDeck.testing();
System.out.println(cardDeck.drawNextCard());
System.out.println(cardDeck.drawNextCard());
System.out.println(cardDeck.drawNextCard());
System.out.println(cardDeck.drawNextCard());
System.out.println(cardDeck.drawNextCard());
System.out.println(cardDeck.drawNextCard());
//System.out.println(cardDeck.drawNextCard());
}
}
You are allocating an array that will only hold 13 cards:
private Card[] cards = new Card[13];
Try making it 52:
private Card[] cards = new Card[52];
In addition to increasing the card array length , In the shuffle function , you are calculating the index using Math.random, that causes ArrayIndexOutbound exception if the index is beyond the card array length. You need to handle this.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
How can i improve on my code such that it would not produce hash values when i call my print method? I reckon the #2a.... etc behind the Card keyword are hash values.
My codes produce the following output when i call my method to print them out:
run:
card.Card#2a139a55
card.Card#15db9742
card.Card#6d06d69c
card.Card#7852e922
My code:
public class Card {
/**
* #param args the command line arguments
*/
static String[] rank = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static String[] suit = {"Spades","Hearts", "Clubs", "Diamonds"};
public Card(String r, String s)
{
}
public static void init(Card[] deck)
{
for(int x = 0; x<deck.length; x++)
{
Card newCard = new Card(rank[x%13], suit[x/13]);
deck[x] = newCard;
}
}
public static void swap(Card[] deck, int a, int b)
{
Card temp = deck[a];
deck[a] = deck[b];
deck[b] = temp;
}
public static void shuffle(Card[] deck)
{
Random rnd = new Random();
for(int x = 0; x<deck.length; x++)
{
swap(deck, x, (rnd.nextInt(deck.length)));
}
}
public static void print(Card[] deck)
{
for(int x = 0; x<deck.length; x++)
System.out.println(deck[x]);
}
public static void main(String[] args) {
// TODO code application logic here
Card[] deck = new Card[52];
init(deck);
print(deck);
}
You should override the toString() method of your class Card.
public String toString()
{
return "I want to print this";
}
The following code separates the duplicate names into 1 column and sum of numbers associated with the names into the second column.
Like :
Nokia 21
Blackberry 3
Nimbus 30
from the array given in the program.
I want to know the final length of the array that contain these entries. In this case 3. How do i calculate that ?
package keylogger;
import java.util.ArrayList;
import java.util.List;
public class ArrayTester {
private static int finalLength = 0;
private static String Name[][];
private static String data[][] = {
{"Nokia" , "7"},
{"Blackberry" ,"1"},
{"Nimbus","10"},
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"},
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"}
};
public void calculator() {
Name = new String[data.length][2];
List<String> marked = new ArrayList<String>();
try {
for(int i=0;i<data.length;i++) {
Name[i][0] = data[i][0];
Name[i][1] = data[i][1];
String name = data[i][0];
if(marked.contains(name)) {
continue;
}
marked.add(name);
int k = i + 1;
int v = k;
for (int j = 0; j < data.length - v; j++) {
String s = data[k][0];
if(Name[i][0].equalsIgnoreCase(s)) {
Name[i][0] = s;
Integer z = Integer.parseInt(Name[i][1]) + Integer.parseInt(data[k][1]);
Name[i][1] = z.toString();
}
k++;
}
}
}catch(Exception exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
ArrayTester o = new ArrayTester();
o.calculator();
for(String s[] : Name) {
for(String x : s) {
System.out.println(x);
}
}
}
}
As usual, the "problem" is poor coding. Your entire program, properly written, can be reduced to just 3 lines of code (5 if you include defining the array and printing the output):
public static void main(String[] args) {
String data[][] = {{"Nokia", "7"}, {"Blackberry", "1"}, {"Nimbus", "10"},
{"Nokia", "7"}, {"Blackberry", "1"}, {"Nimbus", "10"}, {"Nokia", "7"},
{"Blackberry", "1"}, {"Nimbus", "10"}, {"Zebra", "78"}};
HashMap<String, Integer> totals = new HashMap<String, Integer>();
for (String[] datum : data)
totals.put(datum[0], new Integer(datum[1]) + (totals.containsKey(datum[0]) ? totals.get(datum[0]) : 0));
System.out.println("There are " + totals.size() + " brands: " + totals);
}
Output:
There are 4 brands: {Nimbus=30, Zebra=78, Nokia=21, Blackberry=3}
You can't know it a priori, the size will be known just when you'll have finished splitting the strings and doing your math.
In your example in the end marked.size() will have the size you are looking for but I'd suggest you to directly use a HashMap so that you won't care about searching for existing elements in linear time and then convert it to an array.
Something like:
String[][] names = new String[map.size()];
Set<String> keys = map.keys();
int c = 0;
for (String k : keys)
{
names[c] = new String[2];
names[c][0] = k;
names[c++][1] = map.get(k).toString();
}
As far as I understand it, you want to know the number of distinct names in your array without calling calculator(), right? I don't really know if that makes sense as you still have to go through every entry and compare it with a set. But you could do it with a Set:
private int getNumberOfEntries(String[][] data) {
Set<String> names = new HashSet<String>();
for (int i=0; i<data.length; i++) {
names.add(data[i][1]);
}
return names.size();
}
Now you can just call int n = getNumberOfEntries(data);...
EDIT: Of course it makes more sense to do the sums in the same step, see Bohemians solution for that.
Can anybody tell what is the best(easy) way to sort the following string 'index' array in java
String [] menuIndex= { "0",
"1",
"2",
"3",
"0.0",
"0.0.1",
"0.0.0",
"0.0.4",
"14" ,
"14.0",
"0.1" };
I need the sorted array in the following format
0,
0.0,
0.0.0,
0.0.1,
0.0.4,
0.1,
1,
2,
3,
14,
14.0
Plz help....
Since you have changed requirements, your own comparator is the right solution.
import java.util.Arrays;
import java.util.Comparator;
public class MyCmp implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
String[] parts1 = o1.split("\\.");
String[] parts2 = o2.split("\\.");
int max = Math.max(parts1.length, parts2.length);
for (int i = 0; i < max; i++) {
if (i < parts1.length && i < parts2.length) {
Integer i1 = Integer.parseInt(parts1[i]);
Integer i2 = Integer.parseInt(parts2[i]);
if (i1 == i2)
continue;
return i1.compareTo(i2);
}
if (i < parts1.length) {
return 1;
}
if (i < parts2.length) {
return -1;
}
}
return 0;
}
public static void main(String[] args) {
String[] menuIndex = { "0",
"1",
"2",
"3",
"0.0",
"0.0.1",
"0.0.0",
"0.0.4",
"14",
"14.0",
"0.1" };
Arrays.sort(menuIndex, new MyCmp());
System.out.println(Arrays.toString(menuIndex));
}
}
Create your own comparator and sort the array using it.
Use Arrays.sort method for sorting..below is the code.
String [] menuIndex= { "0","1","2","3","0.0","0.0.1","0.0.0","0.0.4","4","4.0","0.1"};
Arrays.sort(menuIndex);
for(String str:menuIndex){
System.out.println(str);
}