Exception in thread "main" java.lang.NumberFormatException: For input string: "; - java

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 ???

Related

issue in debugging code for class

so i'm doing a project for my Computer Science class where i'm building a wheel of fortune game, and for some reason im having an error with debugging my code. if anyone can help, id be very greatful.
** full code in comments wont let me post it ***
public class WheelOfFortune {
private String Hidden;
public WheelOfFortune(String g) {
Hidden = g;
}
public String getHint(String g) {
String letter, HL, result = "";
int x = g.length(), y = 0;
for (int i = 0; i < x; i++) {
letter = g.substring(i, i + 1);
HL = Hidden.substring(i, i + 1);
if (letter.equals(HL)) {
result += letter;
y = Hidden.indexOf(letter);
}
if (y == -1) result = "*";
else result = "+";
return result;
}
}
}
public class Puzzle {
public static void main(String[] args) {
WheelOfFortune guess = new WheelOfFortune("HARPS");
String turn = guess.getHint("AAAAA");
System.out.println(turn);
}
}
Your code didn't even compile because of a missing return statement after the for loop. With this and other errors corrected, your getHint() is:
public String getHint(String g)
{
String letter, HL, result = "";
int x = g.length();
for (int i = 0; i < x; i++)
{
letter = g.substring(i, i + 1);
HL = Hidden.substring(i, i + 1);
if (letter.equals(HL)) result += letter;
else
if (Hidden.contains(letter)) result += "+";
else
result += "*";
}
return result;
}

How to fill array with random values 1-110

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.

Text file load error and array error on mouse island application

I have a problem, I am not looking for answers to my problem I would like some help finding why my array even though specified in main unders switch: case1, case2, case3. I used a for loops with an array that stops at the 5th iteration. However when I run the program it only runs once, am I specifying correctly to make it run 5 times or should it be declared another way? thanks in advance. I should also include there are no errors reported by eclipse at this time until it is ran and only after the first input.
The text files contains
##B##
#---#
#-M-#
#---#
##B##
##B##########
#-----------#
#-----------#
#-----------B
#-----------#
#------M----#
#-----------#
#-----------#
#-----------#
#-----------#
#-----------#
#-----------#
#############
##B#####
#------#
#-M----#
#------#
#------#
#------#
#------#
#####B##
The island maps can be found here
[http://rapidshare.com/share/9704FE33EFF98F1C1E71F6F1DF2DC0D4]
This is the array (int i=0;i<5;i++) however I do not think this is the problem, I can also provide the text files if needed
This is the console out
CS1181 Mouse Island
1. mouseIsland1.txt
2. mouseIsland2.txt
3. mouseIsland3.txt
9. Exit
Please make your selection: 2
Filename: mouseIsland2.txt
Bridge1: 0,0
Bridge2: 0,0
Mouse: 0,0
OUCH! The Mouse fell into the water and died at: 1|1
01
0100000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MouseEscape.runMouseIsland(MouseEscape.java:349)
at MouseEscape.main(MouseEscape.java:71)
End console
import java.io.File;
import java.util.Scanner;
public class MouseEscape {
public static Scanner input = new Scanner(System.in);
public static MouseEscape island1;
public static MouseEscape island2;
public static MouseEscape island3;
private String islandTxt;
private boolean moveDebug;
private int mouseEscaped;
private int mouseDrowned;
private int mouseStarved;
private int islandRows;
private int [] islandCols;
private int runCount;
private int [][] mousePosition;
private int [][] bridgePosition;
private int [][] islandIntArray;
private char [][] islandCharArray;
// main
// Allows the user to select which mouse island map to simulate
public static void main(String[] args) throws Exception
{
System.out.println("CS1181 Mouse Island");
int choice = 0, continueRun = 1;
boolean runResponce = false, correctInput = false;
while (continueRun == 1)
{
System.out.print("\n 1. mouseIsland1.txt"
+ "\n 2. mouseIsland2.txt"
+ "\n 3. mouseIsland3.txt"
+ "\n 9. Exit\n\nPlease make your selection: ");
continueRun = 9;
runResponce = false;
while (correctInput == false){
while (!input.hasNextInt()) {
input.next();
System.out.print("Enter a number 1-3 or 9 to exit.\nPlease make your selection: ");
}
choice = input.nextInt();
if (choice>=1 && choice <=3 || choice == 9){
correctInput = true;
break;
}
}
switch(choice)
{
case 1:
MouseEscape island1 = new MouseEscape("mouseIsland1.txt");
System.out.println("\nFilename: "+island1.getIslandTxt()
+"\nBridge1: "+island1.getBridgePosition(0,0)+","+island1.getBridgePosition(0,1)
+"\nBridge2: "+island1.getBridgePosition(1,0)+","+island1.getBridgePosition(1,1)
+"\nMouse: "+island1.getMousePosition(1,0)+","+island1.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island1.runMouseIsland();
island1.printIslandStats();
correctInput=false; continueRun=1; break;
case 2:
MouseEscape island2 = new MouseEscape("mouseIsland2.txt");
System.out.println("\nFilename: "+island2.getIslandTxt()
+"\nBridge1: "+island2.getBridgePosition(0,0)+","+island2.getBridgePosition(0,1)
+"\nBridge2: "+island2.getBridgePosition(1,0)+","+island2.getBridgePosition(1,1)
+"\nMouse: "+island2.getMousePosition(1,0)+","+island2.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island2.runMouseIsland();
island2.printIslandStats();
correctInput=false; continueRun=1; break;
case 3:
MouseEscape island3 = new MouseEscape("mouseIsland3.txt");
System.out.println("\nFilename: "+island3.getIslandTxt()
+"\nBridge1: "+island3.getBridgePosition(0,0)+","+island3.getBridgePosition(0,1)
+"\nBridge2: "+island3.getBridgePosition(1,0)+","+island3.getBridgePosition(1,1)
+"\nMouse: "+island3.getMousePosition(1,0)+","+island3.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island3.runMouseIsland();
island3.printIslandStats();
correctInput=false; continueRun=1; break;
}
if (runResponce == false)
{
if (continueRun == 1)
{
runResponce = true;
correctInput = false;
}
}
}
input.close();
}
// MouseIslandClass
// Constructs a mouseIslandClass without specifying which mouseIsland to load
public MouseEscape() {
islandTxt = "";
mouseEscaped = 0;
mouseDrowned = 0;
mouseStarved = 0;
islandRows = 0;
runCount = 0;
mousePosition = null;
bridgePosition = null;
islandIntArray = null;
islandCharArray = null;
}
// MouseIslandClass
// Constructs a mouseIslandClass given a mouseIsland map name
public MouseEscape(String _islandTxt) throws Exception{
islandTxt = _islandTxt;
loadIsland();
}
// setIslandTxt
// Sets the mouseIsland filename for the current mouseIsland
public void setIslandTxt(String _islandTxt) throws Exception{
islandTxt = _islandTxt;
}
// getIslandTxt
// Gets the mouseIsland filename for the current mouseIsland
public String getIslandTxt(){
return islandTxt;
}
// getMouseEscaped
// Returns the total number of times a mouse has escaped from the current mouseIsland
public int getMouseEscaped(){
return mouseEscaped;
}
// getMouseDrowned
// Returns the total number of times a mouse has drowned on the current mouseIsland
public int getMouseDrowned(){
return mouseDrowned;
}
// getMouseStarved
// Returns the total number of times a mouse has starved on the current mouseIsland
public int getMouseStarved(){
return mouseStarved;
}
// getBridgePosition
// Returns the coordinate row(x) or column(y) to either of the bridges on the current mouseIsland
public int getBridgePosition(int x, int y){
return bridgePosition[x][y];
}
// getMousePosition
// Returns the coordinate row(x) or column(y) of the mouse on the current mouseIsland
public int getMousePosition(int x, int y){
return mousePosition[x][y];
}
// loadIsland
// Populates any information needed to run the simulation for the current mouseIsland
public void loadIsland() throws Exception{
if (islandTxt == "" || islandTxt == null){
System.out.println("loadIsland() failed! 'islandTxt' variable is empty!");
return;
}
findIslandRow();
findIslandCol();
setCharIslandArray();
findIslandVariables();
}
// printIslandStats
// Prints to the console the statistics for this mouseIsland at its current state
public void printIslandStats(){
System.out.println("Run count: " + runCount + " times\n"
+ "Drowned: " + mouseDrowned + " times\n"
+ "Starved: " + mouseStarved + " times\n"
+ "Escaped: " + mouseEscaped + " times \n");
}
// maxValue
// This function returns the max value of an integer array.
public int maxValue(int [] inArray){
int value = 0;
for (int i=0;i<inArray.length;i++)
if (value<inArray[i]) value = inArray[i];
return value;
}
// findIslandRow
// Counts the number of rows for the current mouseIsland
public void findIslandRow() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
islandRows = 0;
while(input.hasNext()){
input.nextLine();
islandRows++;
}
//System.out.println("Rows: "+islandRows);
input.close();
}
// findIslandCol
// Counts and stores the number of columns for each row in the current mouseIsland
public void findIslandCol() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
String inputLine = ""; int row = 0; islandCols = new int [islandRows];
while(input.hasNext()){
inputLine = input.nextLine();
islandCols[row] = inputLine.length();
//System.out.println("Col"+row+": "+islandCols[row]);
row++;
}
input.close();
}
// loads a mouse island map into a 2 dimensional character array
public void setCharIslandArray() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
islandCharArray = new char [islandRows+1][maxValue(islandCols)+1];
String islandRow ="";
for(int row=0;row<islandRows;row++){
islandRow = input.nextLine();
for (int col=0;col<islandRow.length();col++) {
islandCharArray[row][col] = islandRow.charAt(col);
}
}
input.close();
}
// drawCharIsland
// Draws a character array to the console for testing
public void drawCharIsland() throws Exception{
String ln = "";
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(islandCharArray[row][col]+ln);
}
}
System.out.println("");
}
// drawIntIsland
// Draws an integer array to the console for testing
public void drawIntIsland() throws Exception{
String ln = "";
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(islandIntArray[row][col]+ln);
}
}
System.out.println("");
}
// drawBigIntIsland
// Draws an integer array with special formatting for larger numbers the console for testing
public void drawBigIntIsland() throws Exception{
String ln = ""; String rowZero = ""; String colZero = "";
int i=0;
for (int row= 0;row<islandRows;row++){
if (row <= 9) rowZero = " "; else rowZero ="";
for (int col= 0;col<islandCols[row];col++){
if (row == 0)
while (i<islandRows){
if (i == 0) System.out.print("XY");
if (i <= 9) colZero = " "; else colZero ="";
if (i == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(colZero+i+ln);
i++;
}
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
if (islandIntArray[row][col] <= 9) colZero = "|"; else colZero ="";
if (col == 0) System.out.print(rowZero+row);
if (row >=0 && col >=0) System.out.print(colZero+islandIntArray[row][col]+ln);
}
}
}
// findIslandVariables
// finds and stores all of the mouseIsland object variables
public void findIslandVariables() throws Exception{
int bCount = 0;
mousePosition = new int [2][2]; bridgePosition = new int [200][2];
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
//System.out.println(row+"|"+col);
switch(islandCharArray[row][col]) {
case 'X' : mousePosition[0][0] = row; mousePosition[0][1] = col; //current position
mousePosition[1][0] = row; mousePosition[1][1] = col; //start position
//System.out.println("Mouse found on: "+row+"|"+col);
break;
case '-' :
if (row == 0 || col == 0 || row == islandRows-1 || col == islandCols[row]-1){
bridgePosition[bCount][0] = row; bridgePosition[bCount][1] = col;
bCount++;
//System.out.println("Bridge"+bCount+": "+row+"|"+col);
} else if (col>=islandCols[row-1]-1 || col>=islandCols[row+1]-1){
bridgePosition[bCount][0] = row; bridgePosition[bCount][1] = col;
//System.out.println("Bridge found: "+row+"|"+col);
bCount++;
}
break;
}
}
}
}
// moveMouse
// Computes the movement for the mouse
// set moveDebug to 'true' to display the mouse's moves
public void moveMouse(){
moveDebug = false;
int mouseMove = (int)(Math.random() * 4);
switch(mouseMove){
case 0: mousePosition[0][0]--; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[UP] "); break;
case 1: mousePosition[0][0]++; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[DOWN] "); break;
case 2: mousePosition[0][1]--; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[LEFT] "); break;
case 3: mousePosition[0][1]++; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[RIGHT] "); break;
}
if (moveDebug == true) System.out.println(" Location:|"+mousePosition[0][0]+"|"+mousePosition[0][1]+"|");
}
// runMouseIsland
// Displays the outcome of one trial of the current mouseIsland
public void runMouseIsland() throws Exception{
islandIntArray = new int [islandRows][maxValue(islandCols)];
mousePosition[0][0] = mousePosition [1][0]; mousePosition[0][1] = mousePosition [1][1];
for (int count=0;count<100;count++){
moveMouse();
if (mousePosition[0][0] == bridgePosition[0][0] && mousePosition[0][1] == bridgePosition[0][1] || mousePosition[0][0] == bridgePosition[1][0] && mousePosition[0][1] == bridgePosition[1][1] ){
System.out.println("The mouse has escaped using the bridge at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
mouseEscaped++;
break;
} else
if (islandCharArray[mousePosition[0][0]][mousePosition[0][1]] == '#') {
System.out.println("OUCH! The Mouse fell into the water and died at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
mouseDrowned++;
break;
}
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
if (count == 99){
System.out.println("The mouse withered away (died) at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
mouseStarved++;
}
}
drawIntIsland();
runCount++;
}
}

Unchecked or unsafe operations when compiled, exception when atempted to run

When I attempt to compile my code, this error occurs:
Note: GoFishEdited.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
When I tried to run it, this error message occurs:
Exception in thread "main" java.lang.NullPointerException
at Habitat.stockUp(Habitat.java:20)
at GoFishEdited.main(GoFishEdited.java:14)
I'm pretty sure the error is in the stoockUp method, but I don't understand what could be wrong with it.
Here is my code:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
int[] fishArray;
ArrayList<Fish> catchF = new ArrayList<Fish>();
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
fishArray = h1.stockUp();
System.out.println("Start with some weights:");
for (int i : fishArray) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishArray.length]; // array of Fish
for (int i=0; i < fishArray.length; i++) {
fishGroup[i] = new Fish(fishArray[i]); // make fish
}
System.out.println("Fish are made. Now put them in a habitat:\n");
for (Fish f : fishGroup) {
h1.addFish(f);
}
System.out.println("\nAll in. The habitat displays them:\n");
h1.printFish();
System.out.println("\nMove some fish to the second habitat.\n");
for(Fish f : fishGroup){
h2.addFish(f);
}
System.out.println("\nPrint both habitats:\n");
h1.printFish();
h2.printFish();
System.out.println("\nCatch some fish.\n");
for(Fish f : fishGroup){
catchF = h1.catchFish(f);
}
}
}
And:
public class Habitat {
ArrayList<Fish> stringer = new ArrayList<Fish>();
int[] fishArr;
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public ArrayList<Fish> catches = new ArrayList<Fish>();
public int[] stockUp(){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
return fishArr;
}
public Habitat(){
int[] hab;
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
public ArrayList catchFish(Fish f){
int caught = 0 + (int)(Math.random() * ((100 - 0) + 1));
if(caught < catchProbability){
catches.add(f);
stringer.remove(f);
}
return catches;
}
public void printGrid(int[][] twoD){
int i, j;
for ( i = 0 ; i < twoD.length ; i++ ){
for ( j = 0 ; j < twoD[i].length ; j++ ){
System.out.print( twoD[i][j] + " " );
}
System.out.println();
}
}
public void toGrid(String[] oneD){
int cols = (int) Math.floor(Math.sqrt(oneD.length));
int currentCol = 0;
for(String element : oneD) {
System.out.print(element + "\t");
if(currentCol >= cols) {
System.out.println("");
currentCol = 0;
}
else {
currentCol++;
}
}
}
}
I would appreciate an explanation, because I am thoroughly confused, and just want to see if it'll work properly.
The problem is that you never initialize fishArr in Habitat
And the unchecked operation warning might come from public ArrayList catchFish(Fish f){, you should parameterize your return type

Stuck with Pascal's Triangle in Java

Ok, I need to have a class that re-creates the Pascal Triangle. We are using BlueJ and I can't get my arrays to access each other.
Here's the code:
public class PascalTriangle {
private int currentLineNumber;
private int[] previousLineArray;
private int[] nextLineArray;
public void firstLine()
{
currentLineNumber = 1;
System.out.println("1");
}
public void nextLine()
{
if (currentLineNumber == 1) {
int [] previousLineArray = new int [(currentLineNumber+1)];
previousLineArray[0] = 1;
previousLineArray[1] = 1;
System.out.println("1 1");
currentLineNumber = 2;
}
else if(currentLineNumber >= 2) {
for (int lineCount = currentLineNumber; lineCount <= currentLineNumber; lineCount++) {
int [] nextLineArray = new int [(lineCount+1)];
nextLineArray[0] = 1;
System.out.print(nextLineArray[0] + " ");
for (int nextLineCount = 1; nextLineCount < lineCount; nextLineCount++) {
// The next line is the line with the NullPointerException
nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)
+ previousLineArray[(nextLineCount)]]);
System.out.print(nextLineArray[(nextLineCount)] + " ");
}
nextLineArray[(lineCount)] = 1;
System.out.print(nextLineArray[(lineCount)] + "\n");
previousLineArray = nextLineArray;
}
currentLineNumber = currentLineNumber+1;
}
}
}
The class will compile but as I get to the third line, which should read 1 2 1, I get a java.lang.NullPointerException at PascalTriangle.nextLine(PascalTriangle.java:29) it highlists the nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) line. Why will the nextLineArray take the information from previousLineArray which is set when the nextLine() method is called for the first time?
Any help would be appreciated :) Thanks.
the problem is the following:
in the line where int [] previousLineArray = new int [(currentLineNumber+1)]; - you create a local array that shadows your member and only visible inside of if statement. Then when you come to this line: nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) it uses your member array that was not init.

Categories