我仍然是编程的新手,我知道下面的代码可能一团糟,但是,如何正确使用“ throws子句”?我应该将其用于分配(在主方法标题中添加throws子句),但是当我尝试运行它时,
我收到错误:线程“ main” java.lang.Error中的异常:未解决的编译问题:
此表达式的目标类型必须是功能接口
令牌“引发”的语法错误,请删除此令牌。
我究竟做错了什么?我还应该使用三位十进制格式将均值和标准差打印到输出文件,但是,我也不知道该如何处理。
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class DiceSimulation {
public static void main(String[] args) {
final int NUMBER = 10000; // the number of times to roll the dice
Random generator = new Random();
File myFile = new File("Results");
Scanner inputFile = new Scanner(myFile);
PrintWriter outputFile = new PrintWriter("Results")throws::IOException;
outputFile.println("FileChooser.txt");
outputFile.println("Filereader.txt");
outputFile.println("FileWriter.txt");
outputFile.close();
Scanner keyboard = new Scanner(System.in);
int die1Value; // number of spots on the first die
int die2Value; // number of spots on the second die
int count = 0; // number of times the dice were rolled
int snakeEyes = 0; // number of times snake eyes is rolled
int twos = 0; // number of times double two is rolled
int threes = 0; // number of times double three is rolled
int fours = 0; // number of times double four is rolled
int fives = 0; // number of times double five is rolled
int sixes = 0; // number of times double six is rolled
do {
new Random();
System.out.println("You rolled: ");
die1Value = keyboard.nextInt();
new Random();
System.out.println("You rolled: ");
die2Value = keyboard.nextInt();
} while (count <= 0);
if (die1Value == 1)
;
{
++snakeEyes;
}
if (die1Value == 2)
;
{
++twos;
}
if (die1Value == 3)
;
{
++threes;
}
if (die1Value == 4)
;
{
++fours;
}
if (die1Value == 5)
;
{
++fives;
}
if (die1Value == 6)
;
{
++sixes;
}
++count;
{
System.out.println("You rolled snake eyes " + snakeEyes
+ " out of " + count + " rolls.");
System.out.println("You rolled double twos " + twos + " out of "
+ count + " rolls.");
System.out.println("You rolled double threes " + threes
+ " out of " + count + " rolls.");
System.out.println("You rolled double fours " + fours + " out of "
+ count + " rolls.");
System.out.println("You rolled double fives " + fives + " out of "
+ count + " rolls.");
System.out.println("You rolled double sixes " + sixes + " out of "
+ count + " rolls.");
}
}
}
非常感谢您的帮助,在此先感谢您!
最佳答案
尝试这个:
PrintWriter outputFile = new PrintWriter("Results");
您不必声明构造函数(或与此有关的任何其他方法)在调用构造函数(或方法)时引发异常。我们在方法声明中使用
throws
关键字,而不是实际调用它时。解决此问题后,Java将抱怨抛出了异常,您可以:声明
main()
方法throws IOException
或用
try/catch
语句包围违规行关于java - 如何在Java中正确使用“throws子句”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26321387/