我在如何使我的程序捕获args和op长度的语法上挣扎。我需要它们两个正好是3(3个参数,op必须是3个字符),如果它们不是,我需要它打印出相应的println消息。我是java的新手,所以如果我的代码看起来不愉快或严重错误,我会道歉。
import java.util.*;
public class dd{
public static void main(String[] args)
{
if (args.length !=3)
if (op.length !=3)
{
try
{
int = args.length ;
System.out.println("ok");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("invalid number of arguments");
}
catch( NumberFormatException e )
{
System.out.println("invalid number of characters in operator");
}
finally
{
}
String op = args[2];
int op1 = Integer.parseInt(args[0]);
int op2 = Integer.parseInt(args[1]);
switch(op) {
case "add":
System.out.println(op1+op2);
break;
case "sub":
System.out.println(op1-op2);
break;
}
}
}
编辑:我使用简单的if语句让程序按需运行。我现在的问题是如何使用try catch使程序功能相同?下面的新代码
import java.util.*;
public class tester{
public static void main(String[] args)
{
if (args.length != 3 ){
System.out.println ("Invalid argument");
}
String op = args[2];
int op1 = Integer.parseInt(args[0]);
int op2 = Integer.parseInt(args[1]);
{
if (op.length() !=3){
System.out.println ("Invalid op length");
}
switch(op) {
case "add":
System.out.println(op1+op2);
break;
case "sub":
System.out.println(op1-op2);
break;
}
}
}
}
答案 0 :(得分:0)
我不确定我是否真诚地对你说,但试试这个:
public static void main(String[] args)
{
String op,args1; //you need to declare the variables as string
//you cant use the name args so i changed it to args1
Scanner s = new Scanner(System.in);
op = s.nextLine(); //get the input from the user and put it in op
args1 = s.nextLine(); //get the input from the user and put it in args1
if (args1.length() == 3 && op.length() == 3) //You need to use .length() to get the string length
{
System.out.println("\"args1\" length and \"op\" length is 3 !");
}
else
{
System.out.println("one of the variables \"args1\" or \"op\" or both of them is'nt = 3");
}
}