Gla*_*L33 1 java command-line calculator
这是一个简单的计算器程序.在我的程序继续"添加"输入的两个参数之前,我只需要检查我的数组并防止其中包含任何字母.输入来自命令行,例如java adder 1 2
public class Adder {
public static void main(String[] args) {
//Array to hold the two inputted numbers
float[] num = new float[2];
//Sum of the array [2] will be stored in answer
float answer = 0;
/*
some how need to check the type of agruments entered...
*/
//If more than two agruments are entered, the error message will be shown
if (args.length > 2 || args.length < 2){
System.out.println("ERROR: enter only two numbers not more not less");
}
else{
//Loop to add all of the values in the array num
for (int i = 0; i < args.length; i++){
num[i] = Float.parseFloat(args[i]);
//adding the values in the array and storing in answer
answer += Float.parseFloat(args[i]);
}
System.out.println(num[0]+" + "+num[1]+" = "+answer);
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然您无法"阻止"用户输入字母,但您可以编写代码以便处理字母.以下是几种方法:
1)解析字母,如果找到,扔掉它们.
2)解析字母,如果发现任何字母,则返回错误消息并要求用户再试一次
3)解析数字,并捕获抛出的NFE(NumberFormatException),然后返回错误消息并要求用户再试一次
try {
// your parsing code here
} catch (NumberFormatException e) {
// error message and ask for new input
}
Run Code Online (Sandbox Code Playgroud)
在旁注中,我可能会重写该程序,以便它在while循环中运行,使用Scanner对象来获取输入.这样,每次要添加内容时,都不必使用java命令行运行程序,只需运行程序一次,接受输入直到用户想要退出.它看起来像这样:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
// ask for input
System.out.println("insert 2 numbers separated by a space or quit to quit:")
//scanner object to take input, reads the next line
String tempString = scan.nextLine();
// break out of the loop if the user enters "quit"
if (tempString.equals("quit") {
break;
}
String[] tempArray = tempString.split(" ");
// add the values in tempArray to your array and do your calculations, etc.
// Use the Try/catch block in 3) that i posted when you use parseFloat()
// if you catch the exception, just continue and reloop up to the top, asking for new input.
}
}
Run Code Online (Sandbox Code Playgroud)