我尝试使用 Arrays.toString(array));
打印我的数组但它仍然给了我错误...而且 ELEMENT IS FOUND 是错误的语句,但当我尝试搜索数组中的元素时,它与正确的语句混合,
例如......
I searched 4 in my array: 4 , 2, 3 ,5
但“找到元素”仍然显示。
import java.util.Scanner;
public class linee {
public static void main(String[] args) {
int String;
int value;
Scanner in = new Scanner(System.in);
System.out.print("Input the Number of Element: ");
String n = in.nextLine();
int num = Integer.parseInt(n);
String array[] = new String[num];
for (int i = 0; i < array.length; i++) {
System.out.print("Input the Number at array index " + i + ": ");
array[i] = in.nextLine();
}
Linear(array);
System.out.print("\nDo you want to continue? YES = 1, NO = 2: ");
value = in.nextInt();
if (value == 1) {
main(args);
} else if (value == 2) {
System.out.println("\nThank you for using the program.");
}
}
public static void Linear(String[] array) {
boolean flag = false;
String key = "";
int index = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number that you want to search: ");
key = in.nextLine();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(key)) {
flag = true;
index = i;
}
}
if (flag == true) {
System.out.println("Elements: " + Arrays.toString(array));
System.out.println("ELEMENT IS FOUND AT INDEX " + index);
} else {
System.out.println("ELEMENT IS NOT FOUND");
}
}
}
最佳答案
来自Object.toString(Object[] a)
规范:
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
也就是说,您可能想以另一种方式打印您的元素。一个选项是:
System.out.println("Elements: ");
for(String str: array) {
System.out.println(str);
}
关于java - 我无法打印我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479536/