Whenever I run InschrijvingApplicatie, I get a wrong value out of line System.out.printf("Hoeveel broodjes wil je bestellen? (max %d) ", maxBroodjes); because the int should be "10" when I enter 'p' in this line
System.out.printf("Tot welke categorie behoort u?\nTyp w voor een werknemer, p voor een werknemer met partner, g voor een gast: ");
I'm supposing there is something wrong at the line int maxBroodjes = (inschrijving.geefAantalPersonen() * 5); but can't seem to figure out what.
How the output should look like
The excercise is: for a company that is inviting employees ('w' in the code), employee with a partner ('p') and guests ('g') and letting them fill in their name, what sort of visitor (employee + partner, guest or employee) they are, then asking how many sandwiches the person wants (guest and employee can max require 5 sandwiches, employee+partner can request 10) and the max value is shown in the integer (max %d). All of this is in a loop until the user writes "no" (but the first char is used => resulting in 'n') when asked "Zijn er nog inschrijvingen", and if the answer is yes, it repeats.
Inschrijving.java
package domein;
public class Inschrijving {
private String naam;
private char categorie;
private int aantalBroodjes;
public Inschrijving(String naam, char categorie) {
setNaam(naam);
setCategorie(categorie);
}
public String getNaam() {
return naam;
}
private void setNaam(String naam) {
this.naam = naam;
}
public char getCategorie() {
return categorie;
}
private void setCategorie(char categorie) {
if (categorie == 'w' || categorie == 'p' || categorie == 'g') {
this.categorie = categorie;
} else {
this.categorie = 'g';
}
}
public int getAantalBroodjes() {
return aantalBroodjes;
}
public void setAantalBroodjes(int aantalBroodjes) {
if (aantalBroodjes <= (geefAantalPersonen() * 5)) {
this.aantalBroodjes += aantalBroodjes;
} else {
this.aantalBroodjes += (geefAantalPersonen() * 2);
}
}
public int geefAantalPersonen() {
switch (categorie) {
case 'w':
case 'g':
return 1;
default:
return 2;
}
}
}
InschrijvingApplicatie
package ui;
import domein.Inschrijving;
import java.util.Scanner;
public class InschrijvingApplicatie {
public static void main(String[] args) {
Scanner invoer = new Scanner(System.in);
String antwoord;
char eersteLetter;
System.out.println("Zijn er nog inschrijvingen? ");
antwoord = invoer.nextLine();
eersteLetter = antwoord.toLowerCase().charAt(0);
String naam = null;
String categorie;
char categorieEersteLetter = 0;
int werknemer = 0;
int werknemerMetPartner = 0;
int gast = 0;
int aantalBroodjes;
int tijdelijk;
Inschrijving inschrijving = new Inschrijving(naam, categorieEersteLetter);
if (eersteLetter != 'n') {
do {
System.out.println("Wie mag ik inschrijven? ");
naam = invoer.next();
do {
System.out.printf("Tot welke categorie behoort u?\nTyp w voor een werknemer, p voor een werknemer met partner, g voor een gast: ");
categorie = invoer.next();
categorieEersteLetter = categorie.toLowerCase().charAt(0);
switch (categorieEersteLetter) {
case 'w':
werknemer++;
break;
case 'p':
werknemerMetPartner++;
break;
case 'g':
gast++;
break;
}
} while (categorieEersteLetter != 'w' && categorieEersteLetter != 'p' && categorieEersteLetter != 'g');
int maxBroodjes = (inschrijving.geefAantalPersonen() * 5);
do {
System.out.printf("Hoeveel broodjes wil je bestellen? (max %d) ", maxBroodjes);
tijdelijk = invoer.nextInt();
} while (tijdelijk > maxBroodjes);
aantalBroodjes = tijdelijk;
inschrijving.setAantalBroodjes(aantalBroodjes);
System.out.println("Zijn er nog inschrijvingen? ");
antwoord = invoer.next();
eersteLetter = antwoord.toLowerCase().charAt(0);
} while (eersteLetter != 'n');
}
System.out.printf("Er komen %d werknemer(s) zonder partner, %d werknemer(s) met partner en %d gast(en) naar de receptie. Er dienen %d broodjes besteld te worden.", werknemer, werknemerMetPartner, gast, inschrijving.getAantalBroodjes());
}
}
There are some problems with your approach, it may work but you shouldn't do that way.
First, you store the total sandwiches requested for all invited peopled in only one Inschrijving object, it make no sense! (Do I need to know the total sandwiches requested or only ones requested by me?). So, change setAantalBroodjes in your Inschrijving class to :
public void setAantalBroodjes(int aantalBroodjes) {
this.aantalBroodjes = aantalBroodjes;
}
Second, The requirement is take a list of people and do something with them, so you should consider use a data structure support you store a list of people like an Array or an ArrayList, then you can do whatever you want with your data once user stop input (eersteLetter == 'n' in your case).
List<Inschrijving> inschrijven = new ArrayList<>();
try (Scanner invoer = new Scanner(System.in)) { // http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html
System.out.println("Zijn er nog inschrijvingen? ");
String antwoord = invoer.nextLine();
char eersteLetter = antwoord.toLowerCase().charAt(0);
while (eersteLetter != 'n') {
Inschrijving inschrijving = null;
System.out.println("Wie mag ik inschrijven? ");
String naam = invoer.nextLine();
char categorieEersteLetter = 0;
do {
System.out.printf(
"Tot welke categorie behoort u?\nTyp w voor een werknemer, p voor een werknemer met partner, g voor een gast: ");
String categorie = invoer.nextLine();
categorieEersteLetter = categorie.toLowerCase().charAt(0);
} while (categorieEersteLetter != 'w' && categorieEersteLetter != 'p' && categorieEersteLetter != 'g');
inschrijving = new Inschrijving(naam, categorieEersteLetter);
int maxBroodjes = (inschrijving.geefAantalPersonen() * 5);
int tijdelijk;
do {
System.out.printf("Hoeveel broodjes wil je bestellen? (max %d) ", maxBroodjes);
tijdelijk = invoer.nextInt();
invoer.nextLine(); // https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo
} while (tijdelijk > maxBroodjes);
inschrijving.setAantalBroodjes(tijdelijk);
inschrijven.add(inschrijving);
System.out.println("Zijn er nog inschrijvingen? ");
antwoord = invoer.nextLine();
eersteLetter = antwoord.toLowerCase().charAt(0);
}
}
When the user finished their input:
// Do stuffs with your list of people here
int werknemer = 0;
int werknemerMetPartner = 0;
int gast = 0;
int aantalBroodjes = 0;
for (Inschrijving inschrijving : inschrijven) {
char categorie = inschrijving.getCategorie();
switch (categorie) {
case 'w':
werknemer++;
break;
case 'p':
werknemerMetPartner++;
break;
case 'g':
gast++;
break;
}
aantalBroodjes += inschrijving.getAantalBroodjes();
}
System.out.printf(
"Er komen %d werknemer(s) zonder partner, %d werknemer(s) met partner en %d gast(en) naar de receptie. Er dienen %d broodjes besteld te worden.",
werknemer, werknemerMetPartner, gast, aantalBroodjes);
Because you are new to java, I use a foreach loop here to make example, after learning about OOP and familiar with java, I suggest you reaserch Java 8 Stream api and lambda expression to work with collection types.
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.
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++;
}
}