【发布时间】:2014-02-14 21:38:16
【问题描述】:
我正在编写的程序有问题。这应该是一种猜谜游戏。 该程序将创建一个随机的 4 位数字,其数字不会在任何地方重复。 然后将要求用户输入一个 4 位数字。然后程序会将这个数字与它生成的随机数字进行比较。对于相同且在正确位置的任何数字,它将使变量(比如说A)增加一(1A,2A,3A ...)。对于每个正确但位置错误的数字,它将以相同的方式增加另一个变量(比如说 B)。每次错误答案后,用户将使用打印前的两个变量进行 5 次尝试正确猜测。
我决定将这两个数字存储在一个 int 数组中并尝试以这种方式比较它们(沿着数组的每个元素移动并检查匹配)现在我无法将这两个数字放入数组中。一个打印出 [1, 2, 3, 4] 而用户猜测打印出 [1 2 3 4] 我不确定这是否会有所作为,但我似乎无法弄清楚为什么。
此外,我不确定这是否是比较两个数字的最简单方法,如果我将它们放入数组中,我也不知道该怎么做。也许像这样的陈述?一些指导会很有帮助。
int x = 0;
int y = 0;
if (random[0] == guess[0]){
x+1; }
else if (random[0] == guess[1] || random[0] == guess[2] || random[0] == guess[3])
y+1;
这是我目前所拥有的,我试图从用户那里拆分字符串并将其存储为一个 int,但它说“无法在原始类型 int 上调用 intAt(int)”
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
// create scanner object
Scanner keyboard = new Scanner(System.in);
// give user the game rules
System.out.println("The computer has chosen a unique 4 digit number (No digits in the number repeat)\n"
+ "Each time you guess incorectly you will get a hint. You must guess the number correctly in 5 tries or fewer to win.\n");
// ask user for their guess
System.out.println("Please enter your guess: ");
// read the user input and store it in a string
int input = keyboard.nextInt();
int[] guess1 = new int[4];
for (int i = 0; i < 4; i++) {
guess1[i] = Integer.parseInt(String.valueOf(input.intAt(i)));
}
System.out.println(Arrays.toString(guess1));
}
public static int[] numberGenerator(int[] args) {
// random number generator
Random randy = new Random();
// integer array with 4 positions (for each digit)
int[] randArray = new int[4];
// creates a variable for each position in the array
int rand0 = 0;
int rand1 = 0;
int rand2 = 0;
int rand3 = 0;
// assigns a random value to temporary variable
int a = randy.nextInt(9);
int b = randy.nextInt(9);
int c = randy.nextInt(9);
int d = randy.nextInt(9);
// tests to make sure there are no repeating digits in the number
rand0 = a;
if (b == a) {
b = randy.nextInt(9);
} else
rand1 = b;
if (c == a || c == b) {
c = randy.nextInt(9);
} else
rand2 = c;
if (d == a || d == b || d == c) {
d = randy.nextInt(9);
} else
rand3 = d;
// assigns random integers to their location in the array
randArray[0] = rand0;
randArray[1] = rand1;
randArray[2] = rand2;
randArray[3] = rand3;
// prints and returns the array with its values
System.out.println(Arrays.toString(randArray));
return randArray;
}
// public static String[] compareGuess(String[] args, String str) {
// return guess1;
// }
}
再次,任何关于更简单方法的指导将不胜感激(我是新手,如果可以的话,尽量保持基本的 java)
【问题讨论】:
标签: java arrays parsing int compare