Friday, May 2, 2014

Roll of Dice Problem

Ques:Given an input file of 3000 random dice throws, (here: dice.txt) calculate how many doubles were rolled.It is known for this problem that each die are fair in that they are labeled with the numbers 1,2,3,4,5 and 6. It is also known that a double is defined as both dice showing the same number after they are rolled.

Answer:

Highlights:

1. Use of BufferedReader to read the file
2. Use of string split to read the values input and  compared

======================================================================

package rollofdice;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RollofDice {
 
    public static void main(String[] args) {
        try {
                     
            BufferedReader br=new BufferedReader(new FileReader("d:\\dice.txt"));
            String line;
            String sline[];
              try {
                while((line=br.readLine())!=null){
                    System.out.println(line);
                    sline=line.split(" ");
                        if(sline[0].equals(sline[1])){
                        System.out.println("the roll of die matches");
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(RollofDice.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RollofDice.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
   
}

No comments:

Post a Comment