我正在讓我的程序在Java SE中爲一個學校作業投擲一個東西(如骰子)。用戶可以將一個角色作爲標準輸入,所以用戶選擇的角色將代表骰子的眼睛。有時當我打印結果時,它顯示出完全不同的字符。爲什麼char值在輸出期間轉換?
package ThrowADie;
import java.util.Scanner;
public class ThrowADie {
public static void main(String[] args) {
//Ask user for the char in which the dices eyes should be printed in.
System.out.print("Which character should I use for the eye: ");
//Allow user to place input in the eye variable
Scanner input = new Scanner(System.in); //Make the stdinput object
char eye = input.next().charAt(0);
//Time to throw the die. Place result in dieResult
int dieResult = throwDie();
//Reveal of the result
printDieResult(dieResult, eye);
}
/*
* Method name: throwDie()
* Purpose: Picks a number from 1 to 6 randomly, like a die does
* Parameters: N/A
* Returns: Integer number from 1 to 6
*/
public static int throwDie(){
int range = (6 - 1) + 1;
return (int)(Math.random() * range) + 1;
}
/*
* Method name: printDieResult()
* Purpose: Generate result of the die throw in ASCII art
* Parameters: numberOfEyes, typeOfEyes
* Returns: N/A
*/
public static void printDieResult(int numberOfEyes, char typeOfEyes){
if (numberOfEyes == 1){
//Print art
System.out.println(
" " + " " + " \n"
+ " " + typeOfEyes + " \n"
+ " " + " " + " ");
} else if (numberOfEyes == 2){
//Print art
System.out.println(
typeOfEyes + " " + " \n"
+ " " + " " + " \n"
+ " " + " " + typeOfEyes);
} else if (numberOfEyes == 3){
//Print art
System.out.println(
typeOfEyes + " " + " \n"
+ " " + typeOfEyes + " \n"
+ " " + " " + typeOfEyes);
} else if (numberOfEyes == 4){
//Print art
System.out.println(
typeOfEyes + " " + typeOfEyes + "\n"
+ " " + " " + " \n"
+ typeOfEyes + " " + typeOfEyes);
} else if (numberOfEyes == 5){
//Print art
System.out.println(
typeOfEyes + " " + typeOfEyes + "\n"
+ " " + typeOfEyes + " \n"
+ typeOfEyes + " " + typeOfEyes);
} else {
//Print art
//Accidentally written down 9 eye representation
System.out.println(
typeOfEyes + typeOfEyes + typeOfEyes + "\n"
+ typeOfEyes + typeOfEyes + typeOfEyes + "\n"
+ typeOfEyes + typeOfEyes + typeOfEyes);
}
}
}
輸出 這一計劃將產生正確的結果。但偶爾,已經輸入的代表死亡之眼的字符轉換爲數字。
在下面的情況下,程序應該打印9個'@'字符。相反,它在第一行打印192。 (我知道骰子有6隻眼睛,但我碰到了這個陌生的輸出,而意外打印9隻眼)
run:
Which character should I use for the eyes: @
192
@@@
@@@
我找不到這個原因,任何人都可以看到我做了什麼錯在這裏?
本質上,這些求和之間缺少一個字符串。 – Makoto 2014-09-26 19:44:22
精彩的解釋。我覺得有必要說:謝謝! – Lee 2014-09-26 19:57:08