我正在尝试用Java创建一个识别三角形的程序(只是为了好玩)。这是代码:
import java.util.*;
public class MainClass {
public static void main(String[] args) {
int sides[] = new int[3];
for(int i = 0; i<sides.length; i++){
if(i == 0){
System.out.println("What is the measure of the first side?");
Scanner side1 = new Scanner(System.in);
sides[i] = side1.nextInt();
}
else if(i == 1){
System.out.println("What is the measure of the second side?");
Scanner side2 = new Scanner(System.in);
sides[i] = side2.nextInt();
}
else{
System.out.println("What is the measure of the third side?");
Scanner side3 = new Scanner(System.in);
sides[i] = side3.nextInt();
}
}
if(sides[1] == sides[2] && sides[2] == sides[3]){
System.out.println("It's an equilateral triangle.");
}
else if(sides[1] == sides[2] || sides[1] == sides[3] || sides[2] == sides[3]){
System.out.println("It's an isosceles triangle.");
}
else{
System.out.println("It's a scalene triangle.");
}
}
}
但是,当我运行代码时,它会询问所有三个方面,然后它会引发异常:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at MainClass.main(MainClass.java:29)
。我正确输入所有内容,除上述异常外没有任何错误。你们中的任何人都知道什么是错的,如果是的话,我该如何解决?
答案 0 :(得分:4)
数组索引从0开始而不是1.因此,您需要在第26行修改代码:
if(sides[0] == sides[1] && sides[1] == sides[2]){
System.out.println("It's an equilateral triangle.");
}
else if(sides[0] == sides[1] || sides[1] == sides[2] || sides[0] == sides[2]){
System.out.println("It's an isosceles triangle.");
}