这是我用来确定第一个或最后一个整数是 6 的方法
public Boolean firstLast6(int[] a[]){
int size = a.length;
int x = 0;
for(int i = 0; i < size; i++){
if ((a[i] == 6)&&((i != 0) || (i != size - 1)))
x = 1;
}
if (x == 1){
return true;
}
else{
return false;
}
}
这是我的主要,我认为问题发生的地方
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Enter Numbers with Space: ");
Scanner scan = new Scanner(System.in);
String[] arr = scan.readLine().split(" ");//take the input in string array separated by whitespaces" "
int [] intArr = new int[arr.length];
for (int i = 0; i < arr.length; i++){
intArr[i] = Integer.parseInt(arr[i]);//each array indices parsed to integer
}
Boolean ans = firstLast6(intArr);
if (ans == true){
System.out.println("6 is in the first or last position");
}
else {
System.out.println("6 is not in the first or last position");
}
}
你不需要循环来检查数组的最后一个和第一个索引。
public boolean firstLast6(int[] a){
return a[0] == 6 || a[a.length - 1] == 6;
}
优素福的回答是正确的。然而:
-
firstLast6 必须是静态的才能在 main 中调用,或者您必须创建类的实例。
-
如果未指定数组大小,则应将其读取到 String 数组中,然后使用
Integer.parseInt(arr[i]);
解析其中的每个元素,并将其添加到 int 数组中:String[] arr = scan.nextLine().split(" "); // String array (where your input goes) int[] nums = new int[arr.length]; // int array, where parsed integers will be stored for (int i = 0; i < arr.length; i++) // parsing each String and assigning it to int array nums[i] = Integer.parseInt(arr[i]);
以下是您可以使用的整个代码:
public static Boolean firstLast6(int[] a) {
return a[0] == 6 || a[a.length - 1] == 6;
}
public static void main (String[] args) {
System.out.println("Enter Numbers with Space: ");
Scanner scan = new Scanner(System.in);
String[] arr = scan.nextLine().split(" ");
int[] nums = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
nums[i] = Integer.parseInt(arr[i]);
}
Boolean ans = firstLast6(nums);
if (ans == true){
System.out.println("6 is in the first or last position");
}
else {
System.out.println("6 is not in the first or last position");
}
}