How to fill array with random values 1-110 - java
I want to fill tab[110] array with random bits (so 1 and 0). Don't know how to fill with values 1-110, but not 0-109.
My for-loop:
for (int i = 0; i<tab.length; i++)
{
Random r = new Random();
tab[i] = r.nextInt(2);
if (i%25==0)
{
System.out.println("");
}
System.out.print(tab[i]+"("+i+")"+", ");
}
I know that usually it's simple, just tab[i]=i+1;, but when i put a random number into array it doesn't work for me. I tried to add "+1" everywhere in this loop and only effect i got is when i added it to System.out.println - but then i got fake output that it's 1-110, when in array it's still 0-109.
whole code:
package teleinformatykalab2;
import java.util.Random;
public class TeleinformatykaLab2 {
public static void losujBity(int tab[]) // Funkcja losuje ciag 110 bitow i umieszcza je w utworzonej tabeli
{
System.out.println("Ciag 110 bitow: ");
for (int i = 0; i<tab.length; i++)
{
Random r = new Random();
tab[i] = r.nextInt(2);
if (i%25==0)
{
System.out.println("");
}
System.out.print(tab[i]+"("+i+")"+", ");
}
System.out.println("\n");
}
private static boolean isPowerOfTwo(int x) // Funkcja zwraca liczby, ktore sa kolejna potega liczby 2
{
//return (x & (x-1)) ==0;
return (x!=0) && ((x&(x-1)) ==0);
}
public static void wyswietlBityPowerOfTwo(int tab[])
{
boolean [] bityPotegiDwa = new boolean[7];
System.out.println("Bity, ktorych indeks w tablicy jest kolejna potega liczby 2: ");
for (int i=0; i<tab.length; i++)
{
if (isPowerOfTwo(i))
{
int j = 0;
bityPotegiDwa[j+1] = isPowerOfTwo(i);
j++;
System.out.print(tab[i]+"("+i+")"+", ");
}
}
System.out.println("\n");
}
public static void podzielCiagNaParzysteGrupy(int tab[]) // Funkcja dzieli ciag bitow na 7 grup wg indeksow potegi 2
{
int [] gr1 = new int [56];
}
public static void main(String[] args) {
int [] tab = new int [110]; // Utworzenie tablicy jako globalnej zmiennej
losujBity(tab);
wyswietlBityPowerOfTwo(tab);
podzielCiagNaParzysteGrupy(tab);
}
}
[edit]
Is this proper method? Make tab[111] and then fill it from i=1 to i<=110?
for (int i = 1; i<=110; i++)
{
Random r = new Random();
tab[i] = r.nextInt(2);
if (i%25==0)
{
System.out.println("");
}
System.out.print(tab[i]+"("+i+")"+", ");
}
But then what about tab[0]? Is there null?
[edit2]
My previous version of trying to implement a Hamming code was:
package teleinformatykalab2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
public class TeleinformatykaLab2 {
//Funkcja wypelniajaca tablice ciagiem losowych bitów 0 lub 1 //
static boolean[] bity;
public static void Losowanie(int tab[]){
////int [] tab = new int[110];
for (int i = 0; i<110; i++)
{
Random r = new Random();
tab[i] = r.nextInt(2);
if (i%25==0)
{
System.out.println("");
}
System.out.print(tab[i]+"("+i+")"+", ");
}
System.out.println("");
}
/////////////////
//Funkcja wywietla bity, których indeks w tablicy jest wartoci¹ kolejnej potêgi liczby dwa//
public static void zamienBity(int tab[], int tabBit[])
{
////System.out.println("\n"+tab[0]+tab[109]+"\n");
//int [] power = new int [7];
bity = new boolean[7];
for (int i=0; i<110; i++)
{
if (isPowerOfTwo(i))
{
int j = 0;
bity[j] = isPowerOfTwo(i);
j++;
System.out.print(tab[i]+"("+i+")"+", ");
}
if (i%50==0)
{
System.out.println("");
}
}
System.out.println("\n");
}
//Sprawdzenie ci¹gu kodem Hamminga//
public static void sprawdzHamming(int tab[], int tabBit[])
{
// przypisanie do tabBit bitow o indeksie potêgi dwa
int [] power = new int [7];
for(int i=0;i<tabBit.length;i++)
{
tabBit[i] = tab[(int)Math.pow(2,i)];
System.out.print(tabBit[i]+", ");
}
System.out.println("////\n");
//sprawdzenie pierwszej pary bitów
System.out.println("\nPierwsza para");
int [] skip = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,36,39,41,43,45,47,49,
51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,
101,103,105,107,109};
for (int i : skip)
{
System.out.print(tab[i] + "("+i+")"+",");
if (i%25==0)
{
System.out.println("");
}
}
System.out.println("");
//sprawdzenie drugiej pary bitów
System.out.println("\nDruga para");
int skip2 []= {3,6,7,10,11,14,15,18,19,22,23,26,27,30,31,34,35,38,39,42,43,46,47,
50,51,54,55,58,59,62,63,66,67,70,71,74,75,78,79,82,83,86,87,90,91,94,95,98,99,102,103,106,107};
for (int j : skip2)
{
System.out.print(tab[j] + "("+j+")"+",");
if (j%25==0)
{
System.out.println("");
}
}
System.out.println();
//sprawdzenie trzeciej pary bitów
System.out.println("\nTrzecia para");
int skip3 []= {5,6,7, 12,13,14,15, 20,21,22,23, 28,29,30,31, 36,37,38,39, 44,45,46,47,
52,53,54,55, 60,61,62,63, 68,69,70,71, 76,77,78,79, 84,85,86,87, 92,93,94,95, 100,101,102,103, 108,109};
for (int k : skip3)
{
System.out.print(tab[k] + "("+k+")"+",");
if (k%18==0)
{
System.out.println("");
}
}
System.out.println();
//sprawdzenie czwartej pary bitów
System.out.println("\nCzwarta para");
int skip4 []= {9,10,11,12,13,14,15,16, 25,26,27,28,29,30,31,32, 41,42,43,44,45,46,47,48,
57,58,59,60,61,62,63,64, 73,74,75,76,77,78,79,80, 89,90,91,92,93,94,95,96,
105,106,107,108,109};
for (int l : skip4)
{
System.out.print(tab[l] + "("+l+")"+",");
if (l%8==0)
{
System.out.println("");
}
}
System.out.println();
//sprawdzenie pi¹tej pary bitów
System.out.println("\nPi¹ta para");
for (int m=17; m<110; m++)
{
if ((m>=32 && m<=47) && (m>=64 && m<=79) && (m>=96 && m<=111)) continue;
System.out.print(tab[m] + "("+m+")"+",");
if (m%16==0)
{
System.out.println("");
}
}
System.out.println();
//sprawdzenie szótej pary bitów
System.out.println("\nSzóta para");
for (int m=33; m<110; m++)
{
if (m>=65 && m<=96)/* && (m>=64 && m<=79) && (m>=96 && m<=111))*/ continue;
System.out.print(tab[m] + "("+m+")"+",");
if (m%16==0)
{
System.out.println("");
}
}
System.out.println();
//sprawdzenie siódmej pary bitów
System.out.println("\nSiódma para");
int [] sixtyfour = new int [120];
for (int m=65; m<110; m++)
{
//if (m>=65 && m<=96)/* && (m>=64 && m<=79) && (m>=96 && m<=111))*/ continue;
System.out.print(tab[m] + "("+m+")"+",");
if (m%16==0)
{
System.out.println("");
}
}
System.out.println("\n");
////Tablica liczników par bitów//
int [] counter = new int [7];
////Tablica wywietlanych b³êdów//
Boolean [] error = new Boolean [7];
Boolean [] errors = new Boolean [7];
//////////Liczniki bitów jedynkowych////
int licznik1=0;
for (int a=1; a<110;a++)
{
if (tab[a]==1)
licznik1++;
}
int l1;
String spr;
if (licznik1%2==1) l1=1; else l1=0;
if (l1==tabBit[0]) {
error [0] = true;
errors[0] = true;
}//spr="ok";
else {
error [0]=false;
errors[0] = false;
}
counter [0] = l1;
System.out.println("W grupie 1: "+licznik1+"("+tabBit[0]+")" + " >"+counter[0]+" "+error[0]);
int licznik2=0;
for (int b=3; b<108;b++)
{
if (tab[b]==1)
licznik2++;
}
int l2;
if (licznik2%2==1) l2=1; else l2=0;
if (l2==tabBit[1]) {
error [1]=true;
errors [1]=true;
}
else {
error [1]=false;
errors [1] = false;
}
counter [1] = l2;
System.out.println("W grupie 2: "+licznik2 +"("+tabBit[1]+")"+" >"+counter [1]+" "+error[1]);
int licznik3=0;
for (int c=5; c<109;c++)
{
if (tab[c]==1)
licznik3++;
}
int l3;
if (licznik3%2==1) l3=1; else l3=0;
if (l3==tabBit[2]) {
error[2]=true;
errors [2] = true;
}
else {
error[2]=false;
errors [2] = false;
}
counter [2] = l3;
System.out.println("W grupie 3: "+licznik3 +"("+tabBit[2]+")"+ " >"+counter[2]+" "+error[2]);
int licznik4=0;
for (int d=9; d<109;d++)
{
if (tab[d]==1)
licznik4++;
}
int l4;
if (licznik4%2==1) l4=1; else l4=0;
if (l4==tabBit[3]) {
error[3]=true;
errors [3]=true;
}
else {
error[3]=false;
errors[3]=false;
}
counter[3]=l4;
System.out.println("W grupie 4: "+licznik4 +"("+tabBit[3]+")"+ " >"+counter[3]+" "+error[3]);
//if (l4==tabBit[3]) System.out.print(" ok");
int licznik5=0;
for (int e=17; e<110;e++)
{
if (tab[e]==1)
licznik5++;
}
int l5;
if (licznik5%2==1) l5=1; else l5=0;
if (l5==tabBit[4]) {
error[4]=true;
errors [4]=true;
}
else {
error[4]=false;
errors [4]=false;
}
counter[4] = l5;
System.out.println("W grupie 5: "+licznik5 + "("+tabBit[4]+")"+" >"+counter[4]+" "+error[4]);
int licznik6=0;
for (int f=33; f<110;f++)
{
if (tab[f]==1)
licznik6++;
}
int l6;
if (licznik6%2==1) l6=1; else l6=0;
if (l6==tabBit[5]) {
error[5]=true;
errors[5]=true;
}
else {
error[5]=false;
errors[5]=false;
}
counter [5] = l6;
System.out.println("W grupie 6: "+licznik6+"("+tabBit[5]+")"+" >"+counter[5]+" "+error[5]);
int licznik7=0;
for (int g=65;g<110; g++)
{
if (tab[g]==1)
licznik7++;
}
int l7;
if (licznik7%2==1) l7=1; else l7=0;
if (l7==tabBit[6]) {
error[6]=true;
errors[6]=true;
}
else {
error[6]=false;
errors[6]=false;
}
counter [6] = l7;
System.out.println("W grupie 7: "+licznik7+"("+tabBit[6]+")"+" >"+counter [6]+" "+error[6]);
//Tablica boolean ok lub b³¹d//
ArrayList<Boolean> true_or_false = new ArrayList<>();
for (Boolean tof : true_or_false)
{
int i=0;
i++;
true_or_false.add(error[i]);
System.out.print(tof+",");
}
/*//Dwuwymiarowa tablica bitów i poprawnoci
int [][] bit_check = new int [7][7];
int [] myInt = new int [7];
for (int i=0,j=0; i<7; i++, j++)
{
if (i==0) System.out.println("dwuwymiarowa tablica");
if (errors[i]==false)
{
myInt[i]= (errors[i]) ? 1 : 0;
bit_check[i]=counter;
bit_check[j]=myInt;
System.out.print(bit_check[i][j]+",");
}
}*/
////sumowanie par, które sa blêdne////
ArrayList<Integer> error_sum = new ArrayList<>();
System.out.println("\n");
for (int i=0, j=0; i<7; i++)
{
if (error[i]==false)
{
//System.out.println(counter[i]+" "+error[i]);
error_sum.add(counter[i]);
System.out.println(counter[i]+", ");
}
//System.out.print("//"+power[j]+", ");
//System.out.println("Bity zacne: " + bity[i]);
}
System.out.println("\n");
for (Integer num : error_sum)
{
System.out.print(num+", ");
}
//System.out.println("\n"+error_sum[0]+","+error_sum[1]+","+error_sum[2]+","+error_sum[3]+","+error_sum[4]+","+error_sum[5]+","+error_sum[6]);
System.out.println("\n");
////Sumowanie indeksów b³êdnych bitów//
ArrayList<Integer> error_sum_pair = new ArrayList<>();
/*for (Integer num : error_sum_pair)
{
do{
System.out.print();
}
if (true_or_false==false)
}*/
////Wskazanie blednego bitu, przez sumowanie blednych par bitow//
int suma=0;
int [] grupa = new int [7];
grupa[0] = 1;
grupa[1] = 2;
grupa[2] = 4;
grupa[3] = 8;
grupa[4] = 16;
grupa[5] = 32;
grupa[6] = 64;
for (int i=0; i<7; i++)
{
if (i==0) System.out.print("Numery blednych bitow w grupach: ");
if (error[i]==false)
{
System.out.print(grupa[i]+", ");
suma+=grupa[i];
}
if (i==6) System.out.println("\nIndeks blednego bitu w ciagu: "+suma);
}
int wskOfIndex;
for (int i=0, j=0; i<110; i++)
{
if (j>6) break;
if (i==grupa[j]) System.out.println("Bledny bit we wskazanym "+suma+" indeksie: "+tab[i]);
/*wskOfIndex=Arrays.asList(tab).indexOf(grupa[i]);
if (i==109) System.out.println(wskOfIndex);*/
}
/*////Podmiana blednego bity na prawidlowy//
for (int i=0; i<110; i++)
{
if (i==suma)
{
if (tab[i]==0) tab[i]=1;
else tab[i]=0;
};
}
////Ponowne wygenerowanie, teraz juz prawidlowego ciagu bitow//
for (int i=0; i<110; i++)
{
if (i%25==0)
{
System.out.println("");
}
System.out.print(tab[i]+"("+i+")"+", ");
}
System.out.println("\n");
System.out.println("W grupie 1: "+licznik1+"("+tabBit[0]+")" + " >"+counter[0]+" "+error[0]);
System.out.println("W grupie 2: "+licznik2 +"("+tabBit[1]+")"+" >"+counter [1]+" "+error[1]);
System.out.println("W grupie 3: "+licznik2 +"("+tabBit[2]+")"+" >"+counter [2]+" "+error[2]);
System.out.println("W grupie 4: "+licznik2 +"("+tabBit[3]+")"+" >"+counter [3]+" "+error[3]);
System.out.println("W grupie 5: "+licznik2 +"("+tabBit[4]+")"+" >"+counter [4]+" "+error[4]);
System.out.println("W grupie 6: "+licznik2 +"("+tabBit[5]+")"+" >"+counter [5]+" "+error[5]);
System.out.println("W grupie 7: "+licznik2 +"("+tabBit[6]+")"+" >"+counter [6]+" "+error[6]);*/
}
////Funkcja wypisujaca bity o indeksie w tablicy kolejnej potegi 2//
private static boolean isPowerOfTwo(int x)
{
//return (x & (x-1)) ==0;
return (x!=0) && ((x&(x-1)) ==0);
}
public static void main(String[] args) {
int [] tab = new int[110];
// wywo³anie metody wype³niaj¹cej tablicê ci¹giem losowych bitów 0 lub 1
Losowanie(tab);
System.out.println("\n Bity potegi dwa: ");
int [] tabBit = new int [7];
zamienBity(tab,tabBit);
System.out.println("////Bity potegi 2");
sprawdzHamming(tab,tabBit);
//powerOfTwo();
/*int liczby [] = new int[120];
System.out.println("\n");
for (int z=1; z<120;z++)
{
liczby[z]=z;
System.out.print(liczby[z]+", ");
if (z%32==0)
{
System.out.println("");
}
}*/
}
}
But i noticed that some arrays are wrong built (i forgot that arrays are numbered from 0) and i wanted to rebuild this code, so that i ask how to put random 110 bits into array, but with first bit on 1 index (not standard 0).
In Java arrays are indexed starting from 0. So the index of the 1st element will be 0 and index of the Nth element will be N-1. So since you need to keep 110 bits in an array the arrays will be indexed from 0 - 109.
As an work aground for your requirement of referring to the elements in index that starts from 1, you may write some methods to access the array via 1 based index.
e.g.
int getArrayValue(int[] array, int index){
return array[index-1]
}
void setArrayValue(int[] array, int index, int value){
array[index -1] = value;
}
So that your for loop will logs as follows
for (int i = 1; i<=110; i++)
{
Random r = new Random();
setArrayValue(tab, i,r.nextInt(2));
if (i%25==0)
{
System.out.println("");
}
System.out.print(getArrayValue(tab, i)+"("+i+")"+", ");
}
You can use these methods across your code when you want to access the arrays in a 1 based index.
Related
How to keep BestScores in a File JAVA
I developed a game and I want to keep track of the Top-3 Best Scores in a file, so that we don't lose the Scores after closing the game. It's not working properly and I don't know why. - The Best Scores are Integers, and the lowest it is the better. The Best Score is the lowest. - It is not saving the Scores in ascending Order It does create a file and it appears to work with the main tests but after a few Scores being add, it does not sort the array in ascending order, so the file is in the wrong way. package pt.iscte.dcti.poo.sokoban.starter; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; import pt.iul.ista.poo.utils.Point2D; public class BestScores { public int[] bestScore = new int[3]; public final int level; public BestScores(int level) { this.level = level; } public int[] getBestScore() { return bestScore; } //Register BestScores public void setBestScore(int score) { for(int i = 0; i < bestScore.length; i++) { if(bestScore[i] == 0) { bestScore[i] = score; return; } } Arrays.sort(bestScore); for (int i = 0; i < bestScore.length-1; i++) { if(bestScore[i] == 0) { int box1 = bestScore[i]; bestScore[i] = bestScore[i+1]; bestScore[i+1] = box1; } } addBestScore(score); } public void addBestScore(int score) { if(score < bestScore[bestScore.length - 1]) bestScore[bestScore.length - 1] = score; Arrays.sort(bestScore); for (int i = 0; i < bestScore.length-1; i++) { if(bestScore[i] == 0) { int box1 = bestScore[i]; bestScore[i] = bestScore[i+1]; bestScore[i+1] = box1; } } } public int getTopOne() { return bestScore[0]; } public int getLevel() { return level; } //Check if the file exists, else create it public void searchFile() { File tmpDir = new File("bestScores/BestScore_" + level + ".txt"); if (!tmpDir.exists()) createOrAddScore(); else { checkScores(tmpDir); createOrAddScore(); } } //Create file with Scores if they exist. public void createOrAddScore() { try { PrintWriter writer = new PrintWriter(new File("bestScores/BestScore_" + level + ".txt")); writer.println("BestScores: ************Level:" + level + "************"); for(int i = 0; i < bestScore.length; i++) { if(bestScore[i] != 0) writer.println((i+1) + "º " + bestScore[i] + " " + "moves."); } writer.close(); } catch (FileNotFoundException e) { System.err.println("problema a escrever o ficheiro"); } } //Read File and return Best Scores, so that we don't lose the bestScores even after closing the game :D. public void checkScores(File file) { int[] array = new int[3]; try { Scanner scanner = new Scanner(file); String title_line = scanner.nextLine(); int i = 0; while(scanner.hasNextLine()) { String[] line = scanner.nextLine().split(" "); array[i] = Integer.parseInt(line[1]); i++; } } catch (FileNotFoundException e) { System.err.println("problema a escrever o ficheiro"); } for (int i = 0; i < array.length; i++) if(array[i] != 0) setBestScore(array[i]); } public static void main(String[] args) { // BestScores bS = new BestScores(4); //test1 No BEstScores // bS.searchFile(); //test2 WithBestScores // bS.setBestScore(40); // bS.setBestScore(15); bS.setBestScore(50); // bS.setBestScore(30); // bS.setBestScore(10); // bS.searchFile(); // int[] test = bS.getBestScore(); // for(int i = 0; i < test.length; i++) // System.out.println(test[i]); //test3 With file with Scores // bS.searchFile(); // int[] test = bS.getBestScore(); // for(int i = 0; i < test.length; i++) // System.out.println(test[i]); } }
How to fill a 2d array given values in another class
EDIT: THERE IS NOTHING ABOUT NULL POINTER. NOT A DUPLICATE -The Null pointer exception is what I get so I know I'm not filling the array right, that's what I'm asking. How do I fill the array? I am trying to input the values inside of one class into the 2d array declared into another class. The way it's supposed to work is in the main the nested loop is supposed to supply the values to the other method which is then supposed to input them into the 2d array. Thanks Here is main public class Lab1 { static final int NBPLAYERS = 11; static final int NBMONTHS = 6; public static void main(String[] args) { String[] month = {"April", "May","June", "July", "August","September"}; String[] players ={"Colabello","Donaldson","Smoak","Martin","Goins","Encarnacion","Carrera","Tulow itzki","Pillar","Bautista","Travis"}; double[][] battingAvg = { {0,.368,.300,.224,.386,.268}, {.319,.306,.269,.287,.324,.296}, {.229,.310,.213,.191,.203,.262}, {.197,.327,.239,.256,.138,.213}, {.276,.236,.172,.240,.314,.279}, {.205,.225,.303,.241,.407,.279}, {0,.302,.282,.244,.333,.231}, {0,0,0,.357,.214,.237}, {.273,.181,365,.283,.240,.323}, {.164,.295,.226,.219,.286,.293}, {.325,.189,.313,.368,0,0}}; double [][] onBase = { {.417,.330,.286,.413,.362,.429}, {.370,.373,.322,.370,.408,.403}, {.372,.333,.275,.283,.243,.324}, {.367,.362,.329,.322,.263,.300}, {.323,.278,.221,.286,.442,.347}, {.258,.333,.382,.384,.460,.411}, {0,.357,.333,.277,.333,.313}, {0,0,0,.400,.325,.250}, {.297,.237,.380,.323,.283,.363}, {.325,.418,.388,.300,.370,.436}, {.393,.246,.313,.421,0,0}}; PlayerStats player; BlueJays team = new BlueJays(NBPLAYERS, NBMONTHS); for(int iPlayer=0; iPlayer<NBPLAYERS; iPlayer++) { for(int iMonth=0; iMonth<NBMONTHS; iMonth++) { player = new PlayerStats(players[iPlayer], iMonth, battingAvg[iPlayer][iMonth],onBase[iPlayer][iMonth]); team.setPlayerStatsCell(player,iPlayer,iMonth); } } team.getHighestSingleMonthBattingAvg(); team.getHighestOnBase(5); team.getLowestBattingAvg(5); team.getBestMonth("Bautista"); team.getBestOverallRecord(); team.getLowestOnBase(); The part of this method that I am trying to use ATM is the PlayerStats setPlayerStatsCell(PlayerStats p, int nbPlayers, int nmMonths) Which should, take the information from main and put it into the 2d array. class BlueJays { int nbPlayers; int nbMonths; int j = 0; int highestBattingAvg; int highestBattingMonth; String highestBattingPlayer; int highestOnBase; int lowestAvg; String lowestAvgPlayer; int highestOverall; String highestOverallPlayer; int lowestOnBase; int lowestOnBaseMonth; String highestOnBasePlayer; double bestOverAllMonth; PlayerStats[][] stats; public BlueJays(int nbplayers2, int nbmonths2) { this.nbPlayers = nbplayers2; this.nbMonths = nbmonths2; this.stats = new PlayerStats[nbPlayers][nbMonths]; } PlayerStats setPlayerStatsCell(PlayerStats p, int nbPlayers, int nmMonths) { for(int i=0; i<nbPlayers; i++) { for(int j=0; j<nmMonths; j++) { stats[i][j]= p; } } return p; } PlayerStats getHighestSingleMonthBattingAvg() { j = 0; for(int i = 0; i < nbPlayers; i++) { for(j = 0; j<nbMonths; j++) { stats[i][j].getAvg(); if(highestBattingAvg < stats[i][j].getAvg()) { highestBattingMonth = stats[i][j].getMonth(); highestBattingPlayer = stats[i][j].getName(); } System.out.println("Highest average batting player for the month " + highestBattingMonth + " is " + highestBattingPlayer); } } return null; } PlayerStats getHighestOnBase(int month) { while(j < nbMonths) { for(int i = 0; i < nbPlayers; i++) { stats[i][month].getOnBase(); if(highestOnBase < stats[i][month].getOnBase()) { highestOnBasePlayer = stats[i][month].getName(); } if (i == nbMonths) { j++; i = 0; } System.out.println("Highest average onBase player for the month " + month + highestOnBasePlayer); } } return null; } public PlayerStats getLowestBattingAvg(int month) { j = 0; while(j < nbMonths) { for(int i = 0; i < nbPlayers; i++) { stats[i][month].getOnBase(); if(lowestAvg > stats[i][month].getAvg()) { lowestAvgPlayer = stats[i][month].getName(); } if (i == nbMonths) { j++; i = 0; } } System.out.println("Lowest average batting player for the month " + month + " is " + lowestAvgPlayer); } return null; } PlayerStats getBestMonth(String player) { j = 0; while(j < nbMonths) { for(int i = 0; i < nbPlayers; i++) { stats[i][j].getBoth(); if(bestOverAllMonth > stats[i][j].getAvg() && stats[i][j].getName().contains(player)) { bestOverAllMonth = stats[i][j].getBoth(); } if (i == nbMonths) { j++; i = 0; } } System.out.println("Best month for the player " + player + " is " + bestOverAllMonth); } return null; } public String getBestOverallRecord() { j = 0; while(j < nbMonths) { for(int i = 0; i < nbPlayers; i++) { stats[i][j].getBoth(); if(highestOverall < stats[i][j].getBoth()) { highestOverallPlayer = stats[i][j].getName(); } if (i == nbMonths) { j++; i = 0; } } System.out.println("Highest overall record is " + highestOverallPlayer); } return null; } public PlayerStats getLowestOnBase() { j = 0; while(j < nbMonths) { for(int i = 0; i < nbPlayers; i++) { stats[i][j].getOnBase(); if(lowestOnBase > stats[i][j].getOnBase()) { double lowestOnBase = stats[i][j].getOnBase(); if(lowestOnBase > 0) { lowestAvgPlayer = stats[i][j].getName(); } else { i++; } if (i == nbMonths) { j++; i = 0; } } } System.out.println("Lowest On Base is " + lowestOnBase); } return null; } } Here's the PlayerStats code class PlayerStats { private String name; private int month; private double battAvg, onBase; public PlayerStats(String name, int month, double battingAvg, double onBase2) { this.name = name; this.month = month; this.battAvg = battingAvg; this.onBase = onBase2; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public double getAvg() { return battAvg; } public double getOnBase() { return onBase; } public double getBoth() { return battAvg + onBase; } } And the exception it throws is a Null Pointer, which the array is not filling. Exception in thread "main" java.lang.NullPointerException at BlueJays.getHighestSingleMonthBattingAvg(BlueJays.java:52) at Lab1.main(Lab1.java:52) Highest average batting player for the month 0 is null Highest average batting player for the month 0 is null Highest average batting player for the month 0 is null Highest average batting player for the month 0 is null Highest average batting player for the month 0 is null
Your setPlayerStatsCell function makes no sense in context. Try this one: PlayerStats setPlayerStatsCell(PlayerStats p, int nbPlayer, int nmMonth) { stats[nbPlayer][nmMonth] = p; return p; } The error was caused by the old one not being able to set the last row and column of the table.
CardPile Index Out of bounds
I'm currently trying to convert my code to ArrayList and I can't seem to make it work. I'm running the whole program and it tells me Index out bounds. I'm sure I forgot to add the size of the array for the cards, but I don't know how to add it. Thanks for the help! Edit: The error I get is at the bottom. Also, it tells me to go to the removeTop method. It looks fine there. import java.util.Random; import java.util.List; import java.util.ArrayList; public class CardPile { private ArrayList<Card> cards = new ArrayList<Card>(); private static Random r = new Random(1); public void addToBottom(Card c) { if (this.cards.size() == 52) { System.out.println("The CardPile is full. You cannot add any more Card objects."); } this.cards.add(c); } public Card removeCard(Card c) { if (this.cards.contains(c)) { this.cards.remove(c); } return null; } public Card removeTop() { return this.cards.remove(0); } public int searchValue(int value) { int count = 0, for (int i = 0;i < this.cards.size();i++) { if (this.cards.get(i).getValue() == value) { count++; } } //System.out.println("Count = "+count); return count; } public Card[] removeAll(int value) //System.out.println("(removeAll) cards ="+ cards); int count = searchValue(value); Card[] removed = new Card[count]; int deletedCount = 0; int i = 0; while (deletedCount < count) { if (this.cards.get(i).getValue() == value) { removed[deletedCount] = this.cards.remove(i); deletedCount++; } else { i++; } } return removed; } public int getNumberCards() { return this.cards.size(); } public String toString() { if (this.cards.isEmpty()) { return ""; } String builder = ""; for (int i = 0;i < this.cards.size() - 1;i++) { builder = builder + this.cards.get(i) + ", "; } builder = builder + this.cards.get(this.cards.size() - 1); return builder; } public void shuffle() { if (this.cards.isEmpty()) { return; } for (int count = 0; count < 100000;count++) { int i = r.nextInt(this.cards.size()); int j = r.nextInt(this.cards.size()); Card temp = this.cards.get(i); this.cards.set(i, this.cards.get(j)); this.cards.set(j, temp); } } public static CardPile makeFullDeck() { CardPile deck = new CardPile(); for (int suit = 0;suit < 4;suit++) { for (int value = 1; value <= 13;value++) { deck.addToBottom(new Card(suit, value)); } } deck.shuffle(); return deck; } } **Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.remove(ArrayList.java:492) at CardPile.removeTop(CardPile.java:40) at GoFish.dealCards(GoFish.java:112) at GoFish.main(GoFish.java:13)** EDIT: This is the Player class: public class Player { private boolean[] books; private CardPile pile; private static int MAXIMUM_VALUE_CARD = 13; public Player() { this.pile = new CardPile(); this.books = new boolean[13]; //by default all are false } public boolean hasCard(int value) { return this.pile.searchValue(value) > 0; } public Card[] removeAll(int value) { return this.pile.removeAll(value); } public void addAll(Card[] cards) { for (int i = 0; i < cards.length; i++) { this.pile.addToBottom(cards[i]); } } //optional additional method public void addCard(Card card) { this.pile.addToBottom(card); } public int getNumberCards() { return this.pile.getNumberCards(); } public int countBooks() { int count = 0; for (int i = 0; i < MAXIMUM_VALUE_CARD; i++) { if (books[i]) { count++; } } return count; } public void addBook(int value) { this.books[value - 1] = true; } public void printHand() { System.out.println("Player's hand is " + this.pile); } } And this is the GoFish class: import java.util.Scanner; public class GoFish { private static Scanner reader; public static void main(String[] args) { System.out.println("How many players?"); reader = new Scanner(System.in); int numberPlayers = reader.nextInt(); Player[] players = createPlayersArray(numberPlayers); int currentTurn = 0; CardPile deck = CardPile.makeFullDeck(); dealCards(deck, players); int maximumRetries = 2; int numRetries = 0; while(deck.getNumberCards() > 0 && players[currentTurn].getNumberCards() > 0) { updateBooks(players[currentTurn]); if (numRetries == maximumRetries) { numRetries = 0; currentTurn++; if (currentTurn == numberPlayers) { currentTurn = 0; } } System.out.println("Player " + currentTurn + ", here is your hand. What card would you like to ask for?"); players[currentTurn].printHand(); int queryCard = reader.nextInt(); System.out.println("And from whom would you like to get it from?"); int queryPlayer = reader.nextInt(); if (queryCard < 1 || queryCard > 13 || queryPlayer < 0 || queryPlayer >= numberPlayers || queryPlayer == currentTurn) { System.out.println("Invalid entries. Please retry"); numRetries++; } else { numRetries = 0; boolean hasCard = players[queryPlayer].hasCard(queryCard); if (hasCard) { System.out.println("Cards found!"); Card[] removed = players[queryPlayer].removeAll(queryCard); players[currentTurn].addAll(removed); } else { System.out.println("Go fish!"); Card top = deck.removeTop(); System.out.println("You drew " + top); players[currentTurn].addCard(top); //check to make sure this extra card didn't form a book //Note this could happen even if it doesn't match the card they were asking about updateBooks(players[currentTurn]); if (top.getValue() == queryCard) { System.out.println("You successfully went fishing!"); } else { currentTurn++; if (currentTurn == numberPlayers) { currentTurn = 0; } } } } } //calculate the winner now int maxPlayer = 0; int maxPlayerBooks = players[0].countBooks(); for (int i = 1; i < numberPlayers; i++) { int currentBooks = players[i].countBooks(); if (currentBooks > maxPlayerBooks) { maxPlayer = i; maxPlayerBooks = currentBooks; } } System.out.println("Congratulations! Player " + maxPlayer + " you have won the game by accumulating " + maxPlayerBooks + " books!"); } private static Player[] createPlayersArray(int numPlayers) { Player[] players = new Player[numPlayers]; for (int i = 0; i < numPlayers; i++) { players[i] = new Player(); } return players; } private static void dealCards(CardPile deck, Player[] players) { final int NUMBER_CARDS_PER_PLAYER = 7; for (int i = 0; i < NUMBER_CARDS_PER_PLAYER * players.length; i++) { Card next = deck.removeTop(); players[i % players.length].addCard(next); } } private static void updateBooks(Player player) { for (int i = 1; i <= 13; i++) { //alternative option would be to modify the hasCard method to return an int instead of boolean. Then we could just count (this is probably better design) Card[] valued = player.removeAll(i); if (valued.length == 4) { player.addBook(i); } else { player.addAll(valued); } } } }
How to use Multiple classes and methods in Java in which each class gets values from user
In this program i created simple addition, multiplication and transpose of given matrix a & b. I use three classes, in first class i get row and columns values from user and in second class, i created 7 methods. In first method i get values for matrix a & b from user. I get error from this first method of second class. i enclosed with output what error i get earlier. import java.util.*; class InitialValues { int row,col; int taa = 0, tbb = 0, sum = 0, mul = 0; void init() { Scanner ip1 = new Scanner (System.in); System.out.print("Enter Row and column size : "); row = ip1.nextInt(); col = ip1.nextInt(); System.out.println(); System.out.println("Row & Column : "+row+ " & " + col); } } class GetdValue extends InitialValues { int [][] a = new int [row][col]; int [][] b = new int [row][col]; int i=0,j=0; Scanner ip = new Scanner (System.in); void getVal() { System.out.println("Enter A & B values"+" which having "+row+ " rows & " + col+" columns\n"); for (i=0;i<row;i++) { for(j=0;j<col;j++) { a[i][j] = ip.nextInt(); b[i][j] = ip.nextInt(); //aa[i][j] = a [i][j]; //bb[i][j] = b [i][j]; } System.out.println("\n"); } } { int [][] aa = a; int [][] bb = b; } void displayA() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { System.out.print(a[i][j]+" " ); } System.out.println("\n"); } } void displayB() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { System.out.print(b[i][j]+" " ); } System.out.println("\n"); } } /*void displayAdd() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { sum = a[i][j]+b[i][j]; System.out.print(sum+" " ); } System.out.println("\n"); } } void displayMul() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { mul = a[i][j]*b[i][j]; System.out.print(mul+" " ); } System.out.println("\n"); } } /*void displayTransposeA() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { taa = aa[j][i]; System.out.print(taa+" " ); } System.out.println("\n"); } } void displayTransposeB() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { tbb = bb[j][i]; System.out.print(tbb+" " ); } System.out.println("\n"); } }*/ } class Matrixx { public static void main (String arg[]) { //InitialValues in = new InitialValues(); //in.init(); System.out.println(); GetdValue ob = new GetdValue(); ob.init(); ob.getVal(); //ob.displayA(); //ob.displayB(); } } output: Enter Row and column size : 2 2 Row & Column : 2 & 2 Enter A & B values which having 2 rows & 2 columns Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at GetdValue.getVal(Matrixx.java:37) at Matrixx.main(Matrixx.java:136)
The row and col (defined in the super class) are zeros at the moment when you allocate space for the a and b arrays. So actually you create two arrays a and b of sizes [0][0]. And so you get this exception when you try accessing a[0][0]. You should give some non-zero values to row and col. See your fixed code below. Note the init method in GetdValue. import java.util.*; class InitialValues { int row, col; int taa = 0, tbb = 0, sum = 0, mul = 0; void init() { Scanner ip1 = new Scanner(System.in); System.out.print("Enter Row and column size : "); row = ip1.nextInt(); col = ip1.nextInt(); System.out.println(); System.out.println("Row & Column : " + row + " & " + col); } } class GetdValue extends InitialValues { int[][] a; int[][] b; int i = 0, j = 0; Scanner ip = new Scanner(System.in); public void init(){ super.init(); a = new int[row][col]; b = new int[row][col]; } void getVal() { System.out.println("Enter A & B values" + " which having " + row + " rows & " + col + " columns\n"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { a[i][j] = ip.nextInt(); b[i][j] = ip.nextInt(); // aa[i][j] = a [i][j]; // bb[i][j] = b [i][j]; } System.out.println("\n"); } } { int[][] aa = a; int[][] bb = b; } void displayA() { for (i = 0; i < col; i++) { for (j = 0; j < row; j++) { System.out.print(a[i][j] + " "); } System.out.println("\n"); } } void displayB() { for (i = 0; i < col; i++) { for (j = 0; j < row; j++) { System.out.print(b[i][j] + " "); } System.out.println("\n"); } } /* * void displayAdd() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { sum = * a[i][j]+b[i][j]; System.out.print(sum+" " ); } System.out.println("\n"); * } } * * void displayMul() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { mul = * a[i][j]*b[i][j]; System.out.print(mul+" " ); } System.out.println("\n"); * } } * * * /*void displayTransposeA() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { * taa = aa[j][i]; System.out.print(taa+" " ); } System.out.println("\n"); * } } * * void displayTransposeB() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { tbb * = bb[j][i]; System.out.print(tbb+" " ); } System.out.println("\n"); } } */ } class Matrixx { public static void main(String arg[]) { // InitialValues in = new InitialValues(); // in.init(); System.out.println(); GetdValue ob = new GetdValue(); ob.init(); ob.getVal(); // ob.displayA(); // ob.displayB(); } }
Declare a and b arrays in InitValues class and initialize them in your init method after row and col initialization.
Exception in thread "main" java.lang.NumberFormatException: For input string: ";
I get no compiler errors, but I get this when I run the program and trying to run case 1, the method lesFraFil(): Exception in thread "main" java.lang.NumberFormatException: For input string: "; " at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Hybelhus.lesFraFil(Oblig4.java:63) at Hybelhus.oversikt(Oblig4.java:134) at Hybelhus.meny(Oblig4.java:107) at Oblig4.main(Oblig4.java:23) I have tried asking all my classmates, but none of them were able to help me. import easyIO.*; class Oblig4{ public static void main(String[] args) { int[] antallHybler = new int[18]; for (int i = 0; i < args.length; i++) { antallHybler[i] = Integer.parseInt(args[i]); } Hybelhus hh = new Hybelhus(antallHybler); hh.meny(); } }class Hybelhus{ Out skjerm = new Out(); In lesFil = new In("Hybeldata.txt"); In tast = new In(); Out skrivTilFil = new Out("Hybeldata.txt", true); Hybel[][] hybler = new Hybel[3][6]; void lesFraFil(){ int maaned = lesFil.inInt(";"); int aar = lesFil.inInt(";"); int totFortjeneste = lesFil.inInt(";"); int totAntallMåneder = lesFil.inInt(";"); int månedsleieVanligHybel = lesFil.inInt(";"); int månedsleieToppEtasjeHybel = lesFil.inInt(";"); skjerm.outln(maaned + ", " + aar + ", " + totFortjeneste + ", " + totAntallMåneder + ", " + månedsleieVanligHybel + ", " + månedsleieToppEtasjeHybel); while(!lesFil.endOfFile()){ for(int i = 0; i < hybler.length; i++){ for(int j = 0; j < hybler[i].length; j++){ String tekst = lesFil.inLine(); if(lesFil == null){ continue; } String[] enArray = tekst.split("; "); hybler[i][j] = new Hybel(); hybler[i][j].etasje = Integer.parseInt(enArray[0])-1; hybler[i][j].rom = enArray[1].charAt(0); hybler[i][j].leietager.saldo = Integer.parseInt(enArray[2]); hybler[i][j].leietager = new Student(enArray[3]); } } } } Etasjer[] etasje = new Etasjer[3]; Hybelhus(int[] antallHybler) { for(int i = 0; i < etasje.length; i++){ etasje[i] = new Etasjer(antallHybler[i]); } } void SkrivUt() { for(int i = 0; i < etasje.length; i++){ System.out.println("hei"); } } void meny() { int aksjon = 0; while (aksjon != 8) { skjerm.outln("\nMENY"); skjerm.outln("1. Skriv oversikt"); skjerm.outln("2. Registrer ny leietaker"); skjerm.outln("3. Registrer betaling fra leietaker"); skjerm.outln("4. Registrer frivillig utflytting"); skjerm.outln("5. Månedskjøring av husleie"); skjerm.outln("6. Kast ut leietakere"); skjerm.outln("7. Øk husleien"); skjerm.outln("8. Avslutt"); aksjon = tast.inInt(); switch (aksjon) { case 1: oversikt(); break; case 2: regLeietaker(); break; case 3: regBetaling(); break; case 4: regUtflytting(); break; case 5: kjorHusleie(); break; case 6: kastUt(); break; case 7: okHusleie(); break; case 8:; avslutt(); break; default: System.out.println ("\nDu må taste inn et av de åtte valgene over"); break; } } } void oversikt() { final int BREDDE1 = 10; final int BREDDE2 = 35; final int BREDDE3 = 25; skjerm.out("Hybel", BREDDE1); skjerm.out("Leietager", BREDDE2); skjerm.out("Saldo", BREDDE3); skjerm.outln("\n----------------------------------------------------\n"); lesFraFil(); } void regLeietaker(){ } void regBetaling() { } void regUtflytting(){ } void kjorHusleie() { } void kastUt(){ } void okHusleie() { } void avslutt() { } } class Etasjer{ Hybel[] hybelNavn; Etasjer(int antallHybler){ hybelNavn = new Hybel[antallHybler]; for(int i = 0; i < hybelNavn.length; i++){ char c = (char) i; c += 'A'; hybelNavn[i] = new Hybel(); } } } class Hybel{ int etasje; char rom; Student leietager; Hybel() { } } class Student{ int saldo; String studentNavn; Student(String studentNavn){ this.studentNavn = studentNavn; } }
I don't understand what this means lesFil.inInt(";");, but to me this method obviously parses a string to an int and returns an int (from my best guess by the name of the method and since you say your program does not show any compile errors). And since ";" is not a number, it throws a NumberFormatException
You need to use a debugger.. the line of code that is throwing this exception is line 63 of Oblig4.java. Because of formatting, I'm not sure which line this is. So look at your source code and goto line 63 and see what you are doing there.. I'm guessing it hybler[i][j].etasje = Integer.parseInt(enArray[0])-1; What you can do is : String temp = enArray[0]; System.out.println(temp); int tempInt = Integer.parseInt(temp)-1; System.out.println(tempInt); hybler[i][j].etasje = tempInt; And you'll see what's going on... (if you don't know how to use a debugger!) Good luck! Solve your problem ???