此代码应该在调用playGame方法时用1和0填充数组gameResult,但是该数组不会填充我尝试分配给它的值,不确定为什么会发生这种情况,我尝试使用整数数组,结果是相同的,但数组仍未填充值。
import java.util.Scanner;
class Main { //Assignment1.java
public static void main(String[] args) {
int number;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number from 1-100: ");
number = keyboard.nextInt();
playGame(number);
keyboard.close();
}
public static String[] playGame( int chosenNumber ){
String[] gameResult = new String[9];
int upper = 100;
int lower = 1;
int middle;
for(int i=0;i<=7;i++){
middle = (lower+upper)/2;
if (chosenNumber < middle) {
gameResult[i]="0";
upper = middle;
}
else{
gameResult[i]="1";
lower = middle;
}
}
System.out.format("Chosen integer %3d: ", chosenNumber);
System.out.println();
return gameResult;
}
答案 0 :(得分:1)
您没有在任何地方显示或使用数组(您正在为某些索引分配值)我修改了main方法,只是为了打印返回的数组以显示值
class Main { //Assignment1.java
public static void main(String[] args) {
int number;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number from 1-100: ");
number = keyboard.nextInt();
String[] arr = playGame(number);
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
keyboard.close();
}
public static String[] playGame(int chosenNumber) {
String[] gameResult = new String[9];
int upper = 100;
int lower = 1;
int middle;
for (int i = 0; i <= 7; i++) {
middle = (lower + upper) / 2;
if (chosenNumber < middle) {
gameResult[i] = "0";
upper = middle;
} else {
gameResult[i] = "1";
lower = middle;
}
}
System.out.format("Chosen integer %3d: ", chosenNumber);
System.out.println();
return gameResult;
}
希望有帮助。