我有一个数组,其中填充了用户的输入,我需要打印它。我尝试但是得到了奇怪的结果。首先我要输入我想要输入多少元素,然后我将输入元素,然后我将打印它们。
例如:
我输入了5 10 23 77 105
我需要像这样打印:Elements: 5 10 23 77 105
同样"INVALID INPUT"
位于false
语句中,但它混合在true
语句中。
这是我到目前为止所尝试的内容:
import java.util.*;
import java.util.ArrayList;
public class LinearSearch {
public static void main(String[] args) {
int choice;
Scanner in = new Scanner(System.in);
System.out.println("Choose between INT(1) --- DOUBLE(2) --- STRING(3) --:");
choice = in.nextInt();
if(choice == 1) {
choice(args);
}
}
public static void choice(String[] args) {
int num;
int repeat;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements in the array");
num = in.nextInt();
int array[] = new int [num];
for (int i = 0; i < array.length; i++) {
System.out.print("Enter the number at array index"+i+": ");
array[i] = in.nextInt();
}
System.out.print("Do you want to search if the number is present in the array? YES = 1 , No = 2: ");
int answer = in.nextInt();
if (answer == 1) {
Linear(array);
}
if (answer == 2) {
System.out.println("Thank you for using the program");
}
if (answer >= 3) {
System.out.println("Invalid Input");
}
System.out.print("\nDo you want to repeat the program? Yes = 1 --- No = 2: --- ");
repeat = in.nextInt();
if(repeat == 1) {
main(args);
}
if (repeat == 2) {
System.out.println("Thank you again ! ! !");
System.out.println("Thank you again ! ! !");
System.out.println("Thank you again ! ! !");
System.out.println("Thank you again ! ! !");
System.out.println("Thank you again ! ! !");
System.out.println("Thank you again ! ! !");
System.out.println("Thank you again ! ! !");
}
}
public static void Linear(int array[]) {
int key;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number that you want to search: ");
key = in.nextInt();
for(int i = 0; i < array.length; i++) {
if (array[i] == key) {
System.out.println("Elements: " + array);
System.out.println("Element " + key + " is found at index: " + i);
} else {
System.out.println("INVALID INPUT");
}
}
}
}
答案 0 :(得分:2)
您不应该将数组称为列表。这非常令人困惑。
例如,要打印ArrayList
,您的代码将按预期工作。
但是因为你使用的是数组,而不是
System.out.println("Elements: " + array);
使用
System.out.println("Elements: " + Arrays.toString(array));