[英]Type mismatch: cannot convert from Object Array to int
import java.util.*;
public class tryAgain {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
//Creating array with Children object
Children[] ages = new Children[5];
//Creating new Children ages and adding em to counter
ages[0] = new Children(12);
ages[1] = new Children(10);
ages[2] = new Children (13);
ages[3] = new Children(9);
ages[4] = new Children(15);
sortArray(ages);
System.out.print("Enter the age that you want to search: ");
int val = sc.nextInt();
int res = binarySearch(ages, val);
System.out.println("Value found at index " + res);
}
public static int binarySearch (Children[] ages, int value) {
int[] A = ages;
int n = A.length - 1; // size of an arraylist
int x = value; // value to be searched
boolean isFound = false;
int lowerBound = 1;
int upperBound = n;
int midPoint = 0;
while (isFound = true) {
if (upperBound < lowerBound) {
System.out.println("Searched value doesn't exists.");
}
midPoint = lowerBound + ( upperBound - lowerBound) / 2;
if (lessThan(A[midPoint], x)) {
lowerBound = midPoint + 1;
}
if (lessThan(x, A[midPoint])) {
lowerBound = midPoint - 1;
}
if (A[midPoint] == x) {
isFound = true;
return midPoint;
}
}
return midPoint;
}
public static void sortArray (Children[] ages) {
int n = ages.length;
for (int i = 1; i < n; ++i) {
int key = ages[i];
int j = i - 1;
while (j >= 0 && lessThan(key, ages[i])) {
ages[j + 1] = ages[j];
j = j - 1;
}
ages[j + 1] = key;
}
}
public static boolean lessThan(int x, int y) {
if (y == 0) {
return false;
}
if (x == 0) {
return true;
}
return lessThan(x - 1, y - 1);
}
static class Children {
int age = 0;
//constructor for setting Children ages
public Children (int age) {
this.age = age;
}
//getting ages of Children from constructor
public int getAge() {
return this.age;
}
//setting new age to children
public void setAge(int age) {
this.age = age;
}
}
}
它給了我一個錯誤,例如:類型不匹配:無法從 tryAgain.Children 轉換為 int tryAgain 類型中的方法 lessThan(int, int) 不適用於參數 (int, tryAgain.Children) 類型不匹配:無法從 int 轉換再試一次。孩子們
at tryAgain.sortArray(tryAgain.java:63)
at tryAgain.main(tryAgain.java:19)
目的是在對象數組中添加一些值,然后用排序方法對它們進行排序,然后用二進制搜索找到需要的值。
當你調用這個方法時,你傳遞給它什么?
lessThan(key, ages[i])
key
是一個int
,而ages[i]
是一個Children
(這是不必要的誤導,我們將在下面討論)。 但是該方法期望什么?:
public static boolean lessThan(int x, int y)
一個int
和一個int
。 因此,正如錯誤所述, Children
不能轉換為int
。 大概您打算從Children
對象中獲取年齡:
lessThan(key, ages[i].getAge())
順便說一句……名字很重要。 通過給你的類/變量/等,你基本上把自己弄糊塗了。 誤導性名稱。
什么是Children
? 它是“孩子”的單個實例嗎? 那為什么是復數呢?
什么是ages
? 它是子對象的集合嗎? 那為什么它暗示它只是一個數值的集合呢? (這正是您現在要修復的錯誤。)
將您的Children
類重命名為Child
,因為它代表一個孩子。
將您的ages
變量重命名為children
,因為它代表一組孩子。
通過語義表示的事物來命名事物,您的代碼將更容易閱讀和理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.