我是一名学生,这是我第二周学习Java。任务是从键盘上获取数据,以获取学生姓名,ID和三个测试分数。然后使用JOptionPane显示主要数据。我相信我已经完成了所有这些工作。我将工作分配得更远,这样我也可以了解单元测试。
问题在于ID和测试分数应该是数字。如果输入非数字值,则会得到IOExceptions。我想我需要使用try / catch,但是到目前为止我所看到的一切都让我感到困惑。有人可以解释一下try / catch的工作原理,以便我理解吗?
//Import packages
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* @author Kevin Young
*/
public class StudentTestAverage {
//A reusable method to calculate the average of 3 test scores
public static double calcAve(double num1, double num2, double num3){
final double divThree = 3;
return (num1 + num2 + num3 / divThree);
}
//A method to turn a doule into an integer
public static int trunAve(double num1){
return (int) num1;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException{
//Input variables
String strStudentName = "";
int intStudentID = 0;
double dblScore1 = 0.0;
double dblScore2 = 0.0;
double dblScore3 = 0.0;
String strNumber = ""; //Receives a string to be converted to a number
//Processing variables
double dblAverage = 0.0;
int intAverage = 0;
/**
* Create objects that read keyboard data from a buffer
*/
//Create the reader and Buffer the input stream to form a string
BufferedReader brObject =
new BufferedReader(new InputStreamReader(System.in));
//Get the student's name
do{
System.out.print("Please enter the student's name?");
strStudentName = brObject.readLine();
}while(strStudentName.equals(""));
//Use the scanner to get the student ID
//this method converts the string to an Integer
Scanner scan = new Scanner(System.in);
do{
System.out.print("Please enter the student's ID?");
intStudentID = scan.nextInt();
}while(Double.isNaN(intStudentID));
/*
* The above do while loop with the Scanner isn't working as
* expected. When non-numeric text is entered it throws an
* exception. Has the same issue when trying to use parseInt().
* Need to know how to handle exceptions.
*/
/**
* Us JOption to get string data and convert it to a double
*/
do{
strNumber = JOptionPane.showInputDialog("Please enter the first test score?");
dblScore1 = Double.parseDouble(strNumber);
}while(Double.isNaN(dblScore1));
do{
strNumber = JOptionPane.showInputDialog("Please enter the second test score?");
dblScore2 = Double.parseDouble(strNumber);
}while(Double.isNaN(dblScore2));
do{
strNumber = JOptionPane.showInputDialog("Please enter the third test score?");
dblScore3 = Double.parseDouble(strNumber);
}while(Double.isNaN(dblScore3));
//Calculate the average score
dblAverage = calcAve(dblScore1, dblScore2, dblScore3);
//Truncate dblAverage making it an integer
intAverage = trunAve(dblAverage);
/**
* Display data using the JOptionPane
*/
JOptionPane.showMessageDialog(
null, "Student " + strStudentName + " ID " +
Integer.toString(intStudentID) + " scored " +
Double.toString(dblScore1) + ", " +
Double.toString(dblScore2) + ", and " +
Double.toString(dblScore3) + ".\n For an average of " +
Double.toString(dblAverage));
//Output the truncated average
System.out.println(Integer.toString(intAverage));
}
}
参考方案
您不应使用try-catch块检查数字格式。它是昂贵的。您可以使用以下代码部分。它可能会更有用。
String id;
do{
System.out.print("Please enter the student's ID?");
id = scan.next();
if(id.matches("^-?[0-9]+(\\.[0-9]+)?$")){
intStudentID=Integer.valueOf(id);
break;
}else{
continue;
}
}while(true);
Java Double Object与其他Number类型对象的初始化 - java在Double object documentation中,它只有两个构造函数,一个构造函数使用一个双精度值,另一个构造函数使用一个字符串值。但是,我只是发现,如果我们使用其他Number类型的对象对其进行初始化,它也将起作用。例如,以下代码将起作用:Integer i = Integer.valueOf(10); Double d1 = new Doubl…
Java Double与BigDecimal - java我正在查看一些使用双精度变量来存储(360-359.9998779296875)结果为0.0001220703125的代码。 double变量将其存储为-1.220703125E-4。当我使用BigDecimal时,其存储为0.0001220703125。为什么将它双重存储为-1.220703125E-4? 参考方案 我不会在这里提及精度问题,而只会提及数字…
Java-搜索字符串数组中的字符串 - java在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…
Java Scanner读取文件的奇怪行为 - java因此,在使用Scanner类从文件读取内容时,我遇到了一个有趣的问题。基本上,我试图从目录中读取解析应用程序生成的多个输出文件,以计算一些准确性指标。基本上,我的代码只是遍历目录中的每个文件,并使用扫描仪将其打开以处理内容。无论出于何种原因,扫描程序都不会读取其中的一些文件(所有UTF-8编码)。即使文件不是空的,scanner.hasNextLine()在…
Java Globbing模式以匹配目录和文件 - java我正在使用递归函数遍历根目录下的文件。我只想提取*.txt文件,但不想排除目录。现在,我的代码如下所示:val stream = Files.newDirectoryStream(head, "*.txt") 但是这样做将不会匹配任何目录,并且返回的iterator()是False。我使用的是Mac,所以我不想包含的噪音文件是.DS_ST…