user2856943
user2856943

Reputation:

Why doesnt my output have () around repeating numbers and why doesnt it work?

package dice.project;
import java.util.Scanner;
import java.util.Random;

public class DiceProject {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your number of rolls:");
        int count = in.nextInt();
        int[]rollDice = new int[count];
        Random values = new Random();

        for(int m=0; m<count; m++)
        {
            rollDice[m]=values.nextInt(6)+1;
        }
        boolean inRun=false;
        for(int m=0; m<rollDice.length; m++)
        {
            if(inRun)
            {
                if(m>0 && rollDice[m]!=rollDice[m-1])
                {
                    System.out.print(")" + rollDice[m]);
                    inRun=false;
                }
            }
            if(!inRun)
            {
                if(m<rollDice.length-1 && rollDice[m]==rollDice[m-1])
                {
                    System.out.print("(" + rollDice[m]);
                    inRun=true;
                }
            }
            System.out.print(rollDice[m]);


         }
            if(inRun)
                System.out.print("(");

                    }
                }

Whats wrong with my program? When I run it i get an exception thing and it won't work?

 at java.util.Scanner.nextInt(Scanner.java:2166)        
 at java.util.Scanner.nextInt(Scanner.java:2119)
 at dice.project.DiceProject.main(DiceProject.java:20)

This is also what shows up when i try the output?

Upvotes: 0

Views: 61

Answers (3)

Nishant
Nishant

Reputation: 1142

ArrayIndexOutOfBounds

Snapshot from eclipse debugger. Clearly, boundary conditions are not checked. When m=0 array element for index m-1 is being looked up which causes ArrayIndexOutOfBoundsExceptionin first iteration itself.

Upvotes: 0

Jayasagar
Jayasagar

Reputation: 2066

With given code getting java.lang.ArrayIndexOutOfBoundsException exception, however after changing for loops it works. I am not sure is that what you want :)

What I did

Changing your for loop variable m from 0 to 1 . It is working fine I guess.

for(int m=1; m<rollDice.length; m++) {
 ....
}

As I tested , for given input 12, I got output as 52562434(44)556.

Upvotes: 0

Jorge Campos
Jorge Campos

Reputation: 23361

In your very first iteration of the second loop you are getting an java.lang.ArrayIndexOutOfBoundsException thats because in that first iteration on this line:

if(!inRun){
    if (m < rollDice.length - 1 && rollDice[m] == rollDice[m - 1]) {

The variable m is 0 at this point and your are trying to get an index that doesnt exist in your array rollDice[m - 1] which will be -1. Fix that and you will see your program running. Maybe you will need to change your logic a bit.

Also try to use an IDE that allows you to debug your application.

Upvotes: 1

Related Questions