在我的程序中,用户确定数组的大小,然后用户输入在数组中以降序存储的值作为“高分数”。然后,用户可以选择更新数组中的值,但是对于执行此任务的函数(insertScore),它不会打印出正确的值。
如果:
存储,并且用户决定更新值,通过插入150,数组应更新为
和50将被删除,虽然由于某种原因,当我运行我的代码时,我会继续得到' [Ljava.lang.Integer; @ 55f96302'?我不知道为什么会发生这种情况,我到处寻找方法来解决这个问题,虽然我似乎找不到其他人遇到过这个问题......
我知道我的错误主要是在insertScore函数中持续存在,但我找不到原因?
这是我的代码,感谢您提供的所有帮助:
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class HighScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many values would you like to set the High Score list too?:");
int userInput = input.nextInt();
Integer[] zeroSet = {};
Integer[] setScores = intialisingHighScores(userInput, zeroSet);
System.out.println("Now Enter the high scores you wish to display:");
Integer[] highScores = printHighScores(setScores, userInput);
System.out.println("The high scores are:");
for (int i=0; i<=(userInput-1); i++){
System.out.println((i+1) + ". " + highScores[i]);
}
while (userInput > 0){
setScores = insertScore(userInput, setScores);
}
}
public static Integer[] intialisingHighScores(int userInput, Integer[] zeroSet){
zeroSet = new Integer [userInput];
for (int index=0; index<=(userInput-1); index++){
zeroSet[index] = 0;
}
return zeroSet;
}
public static Integer[] printHighScores(Integer[] setScores, int userInput) {
Scanner inputNo = new Scanner(System.in);
for (int i=0; i<=(userInput-1); i++){
int scores = inputNo.nextInt();
if(scores<0){
System.out.println("No player can be that bad, please enter positive high scores only");
scores = inputNo.nextInt();
setScores[i] = scores;
}
else{
setScores[i] = scores;
}
}
Arrays.sort(setScores, Collections.reverseOrder());
return setScores;
}
public static int higherThan(Integer[] setScores){
Scanner inputNo = new Scanner(System.in);
System.out.println("Please enter any updated scores");
int newScore = inputNo.nextInt();
return newScore;
}
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores);
}
}
}
return setScores;
}
}
答案 0 :(得分:2)
当您使用System.out.println(setScores);
时,您正在调用数组的toString
方法。默认情况下,toString
返回格式为class name @ hex hashcode
的字符串。如果您想要更可读的数组表示,请使用Arrays#toString
:
System.out.println(Arrays.toString(setScores));
答案 1 :(得分:1)
您正在使用toString直接打印数组,并为您提供 className @ hashCode 。
当您循环浏览列表时,您可能需要使用以下内容:
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores[loop]); //***EDITED***//
}
}
}
return setScores;
}