【发布时间】:2014-11-21 21:53:21
【问题描述】:
我正在编写我的程序,以便在 Java SE 中为学校作业掷骰子(如掷骰子)。用户可以放置一个字符作为标准输入,因此用户选择的字符将代表骰子的眼睛。有时当我打印结果时,它会显示完全不同的字符。
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
@@@
@@@
我找不到原因,谁能看到我在这里做错了什么?
【问题讨论】:
标签: java