在一个名为 Symmetric 的类中,具有 main() 方法。 main() 方法接受任意数量的命令行参数,包括无参数。它确定命令行参数是否对称:第一个等于最后一个,第二个等于倒数第二个,依此类推。如果参数是对称的,则表达式
All args symmetric
已打印。如果发现不对称,则会显示类似
的消息Not symmetric at arg 1:b and 2:a
被打印,其中数字对应于参数索引(从 0 开始),字母对应于实际参数。 运行示例如下。
> javac Symmetric.java
> java Symmetric
All args symmetric
> java Symmetric a
All args symmetric
> java Symmetric a a
All args symmetric
> java Symmetric a b
Not symmetric at arg 0:a and 1:b
> java Symmetric a b a
All args symmetric
> java Symmetric a b a c
Not symmetric at arg 0:a and 3:c
> java Symmetric a b a a
Not symmetric at arg 1:b and 2:a
> java Symmetric c a b a b a c
All args symmetric
> java Symmetric c a b d b a c
All args symmetric
> java Symmetric c a b d r a c
Not symmetric at arg 2:b and 4:r
这是我的代码:
public class Symmetric{
public static void main (String[] args) {
int i =0;
int j=args.length-1;
if (args[i].equals(args[j])==false){
System.out.println ("Not symmetric at arg "+i+":"+args[i]+" and "+j+":"+args[j]);
}
while(args[i].equals(args[j]) && i<=j) {
if (i==j || i==j-1 || i==j-2){
System.out.println ("All args symmetric");
// System.exit(1);
}
i++;
j--;
}
}
}
除了前两个之外,我可以通过上面的所有示例。当我输入
java Symmetric
java Symmetric a
我总是遇到 ArrayIndexOutofBoundsException。没有传入值或者只传入一个值的情况该如何处理?
最佳答案
如果您稍微重新排序代码,以便在使用索引之前始终检查索引,那么您可以通过这些情况。
public class Symmetric{
public static void main (String[] args) {
int i =0;
int j=args.length-1;
boolean sym =true;
while(i < j) {
if (!args[i].equals(args[j])){
System.out.println("Not symmetric at arg "+i+":"+args[i]+" and "+j+":"+args[j]);
sym = false;
break;
}
i++;
j--;
}
if (sym) System.out.println ("All args symmetric");
}
}
关于java - 一个简单的对称类,在 void main (String[] args) 中使用 args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271464/