Java Array index problem - java

cantmano is the index, it starts on 0. Another method increases with cant++.
I recheck that 0 <= cantmano <= 10
public void dibujar(){
//actualiza la pantalla
if (cantmano >= 0 && cantmano < 10 && cantcroupier >= 0 && cantcroupier < 10){
TextView textomano = (TextView)findViewById(R.id.textView3);
TextView textocroupier = (TextView)findViewById(R.id.textView5);
CharSequence buffer = textomano.getText();
textomano.setText( buffer + " " +
String.valueOf(manojugador[cantmano].getPalo())+ " de " +
String.valueOf(manojugador[cantmano].getNumero()) ); // <-- ERROR
textocroupier.setText( String.valueOf(cantmano) );
}
}
I get a nice
Caused by: java.lang.NullPointerException
at com.pruebas.blackjack.blackjack.dibujar(blackjack.java:58)
at com.pruebas.blackjack.blackjack.onCreate(blackjack.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2717)
EDITS:
.getNumero() returns the int with the value of a requested CARD. (playing card type)
.getPalo() returns an int where 1= diamonds, etc.
initialization of manojugador:
Carta manojugador[]= new Carta[10];
constructor of Carta:
public Carta(){
int palo=0;
int numero=0;
}
MIDNIGHT UPDATE:
With some improvements i managed it to get over the error. BUT now the array has all 0 values when written. This has to be an easy to solve but that's the final step before accepting the best answer.
Here's the method that adds cards:
public void hit(View v){
//sacan cartas
if (cantmano < manojugador.length){
manojugador[cantmano]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
manocroupier[cantcroupier]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
cantmano++;
cantcroupier++;
}
dibujar();
}

You must initialize the array and it's elements. If you simply have this:
Carta manojugador[]= new Carta[10];
then all 10 elements of the array will be null. You must also initialize each element. Something like this:
for(int i=0, length=manojugador.length; i<length; i++) {
manojugador[i] = new Carta();
}
Update:
I see that in your hit() method, I see you have:
if (cantmano <= 8) {
Shouldn't that be:
if (cantmano < 10) {
Or even better:
if (cantmano < manojugador.length) {
I think that what is happening in your code to cause the NullPointerException is that manojugador[9] can never be initialized.

Your manojugador array null elements and your cantmano is somehow pointing to one of those null elements.
For instance, let's say you have:
ManoJugador [] cantmano = new ManoJugador[10];
cantmano[0] = new ManoJugador();
cantmano[1] = new ManoJugador();
cantmano[2] = new ManoJugador();
You array beyond index 3 you have nulls. That's why when your try to get the numero of null you get NullPointerException.
EDIT
As per your edit:
Yeap, definitely, you have a null value there. Debug that part and you'll see some null values
hint: System.out.println( java.util.Arrays.toString( someArray ));
Suerte!

Related

can someone help me fix this code(string)-java

I try to write a old maid.
After dealing cards,and sorting, i have two parts of card,one is playerDeck, one is computerDeck. now the pairs need to be removed.but i was stuck at this stage.
for example(just an example )
playerDeck:
'A♡', 'A♢', '8♡', '8♢', '8♠', 'Q♠', '2♠', '4♣', '7♢', '7♣', 'K♣', 'A♡', 'J♡', '9♣', '3♢'
computerDeck:
'3♡','3♣', '10♡','10♠','10♣', '6♡', 'K♡','K♢', 'A♣', 'A♠', '4♢', '7♡','7♠'
String q;
String p;
ArrayStringsTools AA=new ArrayStringsTools();//this is a class that i will use for removing item
for(int i=0;i<playerDeck.length-1;i++){
q=playerDeck[i];
q=q.substring(0,1);//i try to find the first character
p=playerDeck[i+1];//after finding first character, i can compare them,and if they are same, then i can remove them
p=p.substring(0,1);
if(q==p){
AA.removeItemByIndex(playerDeck,26,i);//this is the method that i used for removing same item,i will put this code below
AA.removeItemByIndex(playerDeck,26,i+1);//there are 51 cards in total,player has 26, computer has 25
}
}
public static int removeItemByIndex(String[] arrayOfStrings, int currentSize, int itemToRemove){//this is the method i used for removing item(first is the array of Deck, second is the size of Deck,third is the index of item to remove)
if( arrayOfStrings == null || currentSize > arrayOfStrings.length) {
System.out.println("ArrayStringsTools.removeItemByIndex: wrong call");
return currentSize;
}
if( itemToRemove < 0 || itemToRemove >= currentSize ) {
System.out.println("ArrayStringsTools.removeItem: item "
+ itemToRemove + " out of bounds. Array Unchanged.");
return currentSize;
}
int i;
for( i = itemToRemove; i < currentSize-1; i++){
arrayOfStrings[i] = arrayOfStrings[i+1];
}
arrayOfStrings[i]= null;
return currentSize-1;
i think i wrote correctly, but it doesnt show any difference compared with the origin.
the result should be:
playerDeck: '8♠', 'Q♠', '2♠', '4♣', 'K♣', 'A♡', 'J♡', '9♣', '3♢'
computerDeck:'10♣', '6♡', '4♢'
or is there another way to do this,because when a pair removed,there are two empty spaces, so... I've been struggling for a long time......
To compare the 1st character, change this line
if (q == p) {
to
if (q.charAt(0) == p.charAt(0)) {
Notice that q == p checks to see if the q and p refer to the same string, and do not look at the contents at all. If you want to compare full strings (or any other object that is not a char, an int, or so on) by content, you should use equals: q.equals(p) returns true only if both have the same content.
If you want to compare two strings,you can use 'equals',like
if(q.equals(p)){//q==p if true,they are save in the same location-this may not be what you want,and in this code it will be false forever.
}

How to Fix the Runtime Error : java.lang.ArrayIndexOutOfBoundsException: 0

Here is the problem:
"Say you have an array for which the ith element is the price of a
given stock on day i.
If you were only permitted to complete at most one transaction (ie,
buy one and sell one share of the stock), design an algorithm to find
the maximum profit."
Here is my solution.
public class Solution {
public int maxProfit(int[] prices) {
int[] sell = new int[prices.length];
for(int i = 0; i<prices.length; i++){
for(int j = 0; j<i; j++){
sell[i] = Math.max(prices[i] - prices[j], sell[i]);
}
}
int sellPrice = prices[0];
int day = 0;
for(int i = 0; i<prices.length; i++){
if(sellPrice < prices[i]){
sellPrice = prices[i];
day = i;
}
}
int buyPrice = prices[0];
for(int i = 0; i<day; i++){
buyPrice = Math.min(buyPrice, prices[i]);
}
return sellPrice - buyPrice;
}
}
I'm not sure if it work, which is not a problem now. The problem is, it always shows Runtime Error at Line 9: (int sellPrice = prices[0];)
and
Line 18: (int buyPrice = prices[0];) as "java.lang.ArrayIndexOutOfBoundsException: 0".
So what's wrong with it? How to fix it? Thank you so much.
The only reason prices[0] would throw an AIOOBE is because the prices doesn't have any prices in it.
For example:
public static void main(String[] args)
{
int[] ints = new int[] {};
System.out.println(ints[0]);
}
Throws this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:7)
Whereas this, works.
public static void main(String[] args)
{
int[] ints = new int[] {93727};
System.out.println(ints[0]);
}
Check if you are not passing a zero length array to your maxProfit method and be sure to initialize the array before using it in your method.
Here is the possibilty:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
The array you passing to this method is empty. That is no elements in that array. The part
equal to the size of the array. (size is 0 and index is zero)
That is the cause in your case.
You're getting an exception probably because the prices array was not instantiated correctly.
Also, your algorithm is not guaranteed to be correct: consider the following set of prices,
$4, $5, $1, $3
The maximum profit made would be 2 dollars, but your algorithm would result in $1.
Here's some correct answers: Maximum single-sell profit
How does your main look like??
Make sure the array prices[] is created and also initialized.
If it is created like int[] prices = new int[] {}; you will see an error saying index out of bound.
Make sure you initialize (from user input or using hard coded values).
If it is from user input make sure that the values are assigned.
Hard Coded one will look like this:
int price[] = {100,200,500,2000,700,500,400};
Hope it helps
leetcode
When prices.lenght = 0, prices[] is null at line 9 and 18.
That's why you got errors.

In an array with null spaces, how can consolidate all of the non null values together?

Hey so I have this homework assignment and I'm having issues with one of the methods. I would like hints and not actual answers/code.
So I have a class called HorseBarn that messes with an array of horses(horse being the type). My problem is I'm having troubles with the consolidate method.
What the array would look like before consolidate:
a,b,c,d are horses
|a|null|b|null|c|d|
What the array would look like after consolidate:
|a|b|c|d|null|null|
So my logic would be to make a nested for loop. The first loop would search for a null value, once the first loop finds the null value, the second loop would look for a horse and then swap with it. Then the second loop would end and go back to the first loop. So here is what I have right now and it doesn't work(it just terminates). Is my logic wrong or is it my syntax that's causing the problems?
public void consolidate()
{
int j = 0;
for(int i = 0; i < spaces.length;i++)
{
if( spaces[i] == null)
{
for(j = i; j < spaces.length && spaces[j] == null; j++)
{
}
spaces[i] = spaces[j];
spaces[j] = null;
}
}
Well for starters, this should give an index out of bounds exception if the last non-null is found and there still are elements remaining:
ex: horses = | a | null | null | null |
for i = 1, since horses[1] -> horses[3] are empty, j first gets set to 1 then ends with j = 4 (because of the termination condition j < horses.length())
You would then try to swap horses[1] with horses[4], which throws the array index out of bounds
In the inner for loop, just find the position of next non null value and break it there.
Then swap it with your null.
A better time efficient code.

Getting an"index:0" and "size:0" error from ArrayList.size()

I have been working on this program for hours, and have worked out nearly all of the errors that have cropped up in every other class. This one, however, I can's seem to fix the receive method. The receive method should first check (by comparing SKUs) whether or not the incoming product is already in myCatalog. If not, add the product (via its SKU) to the catalog. After that, in any case -- as long as there is still some of the incoming product not yet been placed in a bin -- I want to locate which bin contains the least total quantity. (If all the bins are full, add a new, empty bin to use)I'd add that specific product to that bin until the bin is either full -- at which point I'd repeat -- or I run out of the product. This repeats until no more incoming product is left.
public class Warehouse
{
private int myBinMax;
private ArrayList<MusicMedia> myCatalog;
private ArrayList<Bin> myBins;
public Warehouse( int binMax )
{
myBinMax = binMax;
myCatalog = new ArrayList<MusicMedia>();
myBins = new ArrayList<Bin>( 5 );
}
public String toString()
{
return Tester.detailedInventory(myCatalog,myBins);
}
public void addBin()
{
myBins.add( new Bin( "B" + myBins.size() ) );
}
public void receive( MusicMedia product, int quantity )
{
boolean contained = false;
int lowestAmount = myBinMax,
leastFullBinIndex,
i,
insertQuantity;
for(MusicMedia entry : myCatalog)
{
if(entry.getSKU().equals(product.getSKU()))
{
contained = true;
}
}
if(!contained)
{
myCatalog.add(product);
}
while(quantity > 0)
{
lowestAmount = myBinMax;
for(i = 0; i < myBins.size(); i++)
{
if(myBins.get(i).totalQuantity() < lowestAmount)
{
lowestAmount = myBins.get(i).totalQuantity();
leastFullBinIndex = i;
}
if((i == myBins.size() - 1 && lowestAmount == myBinMax)||(myBins.size() == 0))
{
myBins.add(new Bin("bin" + Integer.toString(i)));
}
}
if(quantity >= myBinMax - lowestAmount)
{
insertQuantity = myBinMax - lowestAmount;
}
else
{
insertQuantity = quantity;
}
quantity -= insertQuantity;
myBins.get(i).add(new BinItem(product.getSKU(), insertQuantity));
}
}
}
Before my last edit, nothing would print -- just a blank console -- but in an attempt to fix that, I added this (also contained within the code above):
if((i == myBins.size() - 1 && lowestAmount == myBinMax)||(myBins.size() == 0))
{
myBins.add(new Bin("bin" + Integer.toString(i)));
}
Now, it won't run without giving me an error:
java.lang.IndexOutOfBoundsException
Index: 0, Size 0 (in java.util.ArrayList)
As well as highlighting the following line:
myBins.get(i).add(new BinItem(product.getSKU(), insertQuantity));
Here's a breakdown on the various classes that have been created for this colossal program:
MusicMedia has three private variables, but the only one that has any bearing here is the String mySKU, obtained by getSKU()
Bin has a private String, name, which is also its only argument, as well as a private ArrayList of class BinItem. In order to access this ArrayList of BinItems from another class, you would use getContents(). It also has method totalQuantity(), which returns the total quantity of objects already in a bin.
BinItem has private variables mySKU (String) and myQuantity (int) and methods getSKU() and getQuantity(), both being its arguments in that order
So to start with you have no bins.
Your "for" block is skipped because size is zero;
So we get to the final line of the "while" loop, and we execute myBins.get(i)...
This is where we get the error because we can't get the bin at index 0, because we got no bins at all.
The problem is we reached this line of code without adding any bins...
I'm not sure if you realized, the line below doesn't start your program with 5 bins.
myBins = new ArrayList<Bin>( 5 );
The 5 in this code sets the internal buffer for the array to hold 5 items. If we supplied no number it would start with 10. But the numbers are just there to give programmers control over how much memmory is initalized.
If your goal was to start with 5 bins, you should do something as follows:
myBins = new ArrayList<Bin>( 5 );
for(int i=0; i<5; i++){
myBins.add(new myBin());
}

Java: How to write computing data in arraylist?

Hello guys I'am beginner of the Java and i've got some problems with array&arraylist. My main problem is how to write computing, dynamic data into the array and later how to read it? Here's my weird code:
public static void main(String[] args) {
int yil, bolum = 0, kalan;
Scanner klavye = new Scanner(System.in);
ArrayList liste = new ArrayList();
//or shall i use this? >> int[] liste = new int[10];
System.out.println("Yıl Girin: "); // enter the 1453
yil = klavye.nextInt();
do{ // process makes 1453 separate then write in the array or arraylist. [1, 4, 5, 3]
kalan = yil % 10;
liste.add(kalan); //my problem starts in here. How can i add "kalan" into the "liste".
bolum = yil / 10;
yil = bolum;
}while( bolum == 0 );
System.out.println("Sayının Basamak Sayısı: " + liste.size()); //in here read the number of elements of the "liste"
klavye.close();
}
Edit:
//needs to be like that
while( bolum != 0 );
System.out.println("Sayının Basamak Sayısı: " + liste);
I think that you most likely want your loop stopping condition to be:
while( bolum != 0)
because bolum will only be 0 when there are no more digits left in your number to process. Also, as amit mentions above it could be the case that the user entered 0 when prompted for a number, so you should take that into account.
To obtain a string representation of your ArrayList (showing the elements it contains through their string representations), you can just use
System.out.println("Sayının Basamak Sayısı: " + liste);
No need to convert to an array. This works because it causes liste's toString method to be called (which is why we don't need to call it explicitly).
You must change this line:
}while( bolum == 0 );
To this:
}while( bolum > 0 );
If you want to print your elements in the ArrayList, update your last statement to print as below:
System.out.println("Sayının Basamak Sayısı: " + liste);
Or you can iterate your list and print as :
for(Object i: liste){
System.out.println(i);
}
This will print your individual list items in separate lines.
Also please fix your while condition as while(bolum != 0); as it may terminate after the very first iteration as bolum will be non zero i.e. 1, 2...(!= 0).

Categories