0

Im a beginner, self taught trying to work though an assignment. Im trying to create a program that will read in N lines of code based on the first line on input (which is an integer). The other lines of input consist of lines of three letters, either being b, s or f. B and S are the only important letters being read as B adds one point to the player who rolled and more than 3 S's and player loses turn, F's mean nothing. Based on what letters are read, points are assigned to each person per turn. My current roadblock is the char d1 = line[i].charAt(0) area, it is giving me a command exited with a non zero status and Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2.
int num = input.nextInt(); String [] line = new String[num];

for (int i=0; i<num; i++){
ine[i] = input.next(); 


// Creating characters for the dice 
char d1 = line[i].charAt(0);
char d2 = line[i].charAt(2);
char d3 = line[i].charAt(4);

while (aliceScore<3){

//D1 die score - alice
if (d1 == 'b')
aliceScore++;
else if (d1 == 's') 
aliceShotgun++;
else 

//D2 die score - Alice
if (d2 == 'b')
aliceScore++;
else if (d2 == 's')
aliceShotgun++;
else 

//D3 die score - Alice
if (d3 == 'b')
aliceScore++;
else if (d2 == 's')
aliceShotgun++;
else 


if  (aliceShotgun == 3)
aliceScore = 0;
break;  

I expect it to read each line of input and assign d1, d2 and d3 to the three letters in each line and then points can be assigned to each person based on that. An example input would be

3
B B S
S B F
B B F

output Alice: 3, Bob: 2

Madplay
  • 1,027
  • 1
  • 13
  • 25
Zach.L
  • 3
  • 1

2 Answers2

1

Change input.next(); to input.nextLine().

As in short input.next() will only give you a word while input.nextLine() will scan the whole line. You can also try to debug it yourself and see what is happening in each block/line of code.

Note: Make sure your input is correct and each line at-least contains 5 char (line[i].charAt(4)). Otherwise you will again get java.lang.StringIndexOutOfBoundsException. Have a look why this happen: understanding-array-indexoutofbounds-exception-in-java

MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
0

input.next() only read letter up-to space,so instead of input.next() you can change it as input.nextLine()

ex:

for (int i=0; i<num; i++){    
   ine[i] = input.nextLine();    
   String [] a=ine[i].split(" ");    
   char d1 = a[0].charAt(0);    
   char d2 = a[1].charAt(0);    
   char d3 = a[2].charAt(0);
}
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37