我有一个程序,用户必须从线性搜索数组中选择所需的元素。当用户输入1继续时,我的程序应再次显示问题和给定的数组。我不确定while循环必须在哪里以及while循环中应该包含什么代码,因为如果用户输入1继续我的程序,则它不会继续,它只会结束 这是我的代码:
import java.util.Scanner;
public class SearchArray
{
public static int Search(int[] data, int key)
{
for (int i = 0; i < data.length; i++)
{
if (data[i] == key)
{
return i;
}//end of if statement
}//end of for loop
return -1;
}//end of search method
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] data= {74,56,45,14,78,100};
for(int element: data)
{
System.out.print(element + " , ");
}
System.out.println("Enter the key of your choice: ");
int key = in.nextInt();
int index = Search(data, key);
int option = 1;
System.out.println("Enter 1 to continue: ");
while(option ==1)
{
option=in.nextInt();
}
if(index!=-1)
{
System.out.println("Key: " + key + " Found at index: " + Search(data, key));
}//end of if statement
else
{
System.out.println("Key: " + key + " Is not found ");
}//end of else statement
}//end of main method
}//end of main class
答案 0 :(得分:0)
创建自己的新类。即
if(sc.nextInt() == 1){
SearchArray sa = new SearchArray();
sa.main();
}
答案 1 :(得分:0)
尝试使用这种主要方法
public static void main(String... args) {
Scanner in = new Scanner(System.in);
int[] data = {74, 56, 45, 14, 78, 100};
for (int element : data) {
System.out.print(element + " , ");
}
while (true) {
System.out.println("Enter the key of your choice: ");
int key = in.nextInt();
int index = Search(data, key);
System.out.println("Key: " + key + " Found at index: " + index);
System.out.println("Enter 1 to continue: ");
while (in.nextInt() != 1) {
System.out.println("Enter 1 to continue: ");
}
}
}