while programming the game mastermind I became stuck when having to figure out how to come up with the correct integers and i will figure the sum for these after i find them
for example
secretCode = 123
input = 222
output is correct integers: 1 and sum: 2
for input = 122
output is correct integers: 2 and sum: 3
Name:
Anonymous2009-03-17 2:31
Like this?
import java.util.Scanner;
import java.util.Random;
public class Mastermind {
public static final int DEFAULTCODELENGTH = 3;
private String code;
private int codeLength;
private int turns;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for(;;) {
System.out.println("Would you like to play a game of matermind? (y/n)");
if(sc.nextLine().toUpperCase().indexOf("Y")>=0) {
System.out.println("How long would you like the code to be? (Default "+Mastermind.DEFAULTCODELENGTH+")");
int codeLength = Mastermind.DEFAULTCODELENGTH;
try {
codeLength = Integer.parseInt(sc.nextLine());
if(codeLength<=0 || codeLength>80) throw new NumberFormatException("Invalid code length");
}
catch(NumberFormatException e) {
System.out.println("Invalid code length, defaulting to three.");
codeLength = Mastermind.DEFAULTCODELENGTH;
}
Mastermind game = new Mastermind(codeLength);
game.play();
}
}
}
public Mastermind(int codeLength) {
Random rand = new Random();
this.code = "";
this.turns = 0;
this.codeLength = codeLength;
int character;
for(int i=0; i<codeLength; i++) {
code+=rand.nextInt(10)+"";
}
}
public void play() {
Scanner scan = new Scanner(System.in);
for(;;) {
System.out.println("Make a guess!");
String input = scan.nextLine();
try {
Integer.parseInt(input); //NaN
if(input.length()!=codeLength) throw new NumberFormatException("Invalid input!");
int sum = 0, num = 0;
for(int i=0; i<codeLength; i++) {
if(code.charAt(i)==input.charAt(i)) {
sum+=Integer.parseInt(code.charAt(i)+"");
num++;
}
}
turns++;
System.out.println("Number of correct integers: "+num);
System.out.println("Sum of correct integers: "+sum);
if(code.equals(input)) {
System.out.println("You completed the puzzle in "+turns+" turns!");
return;
}
}
catch(NumberFormatException e) {
System.out.println("Invalid input specified! Must be a number with exactly "+codeLength+" digits.");
}
}
}
}