java - 我试图让我的程序继续请求输入并回答该输入

标签 java arrays

我这里有一个程序,它从输入文件中读取数字列表,然后要求用户输入一个数字。然后程序查看文件,如果用户输入的数字在文件中,则会显示“此数字在文件中”,如果该数字不在文件中,程序将显示“数字不在文件中”文件。”然后,程序必须不断要求用户输入数字,并根据输入的数字,写回适当的响应。第一次要求用户输入数字时,程序正常工作并打印回正确的响应,问题是程序再次要求输入数字后,它将打印回与第一次输入的数字相同的响应 no无论输入什么数字,无论它是否在文件中。我的 while 循环在错误的位置吗?不知道如何解决这个问题。

package classwork7_2;
import java.util.*;
import java.io.*;

public class ClassWork7_2 {

public static void main(String[] args)throws IOException {

    Scanner s = new Scanner(System.in);

    int[] numbers = fileToArray();
    Arrays.sort(numbers);

    System.out.print("Enter a number in the file: ");
    int numb = s.nextInt();

    int i = Arrays.binarySearch(numbers, numb);

    if(i < 0){
        while(i < 0){
        System.out.print("Number is not in file\n");
        System.out.print("Enter number in the file: ");
        s.nextInt();
        }
    }

     else if(i >= 0){
         while(i >= 0){
        System.out.print("This number is in the file\n");
        System.out.print("Enter number in the file: ");
        s.nextInt();
         }
    }
}

public static int[] fileToArray() throws IOException{

    Scanner s = new Scanner(System.in);
    int[] array = new int[7];

    System.out.print("Enter name of file: ");
    String filename = s.nextLine();

    File f = new File(filename);
    Scanner inputFile = new Scanner(f);
    int i = 0;

    while(inputFile.hasNext()){

       array[i] = inputFile.nextInt();
       i++;
    }
        inputFile.close();
        return array;
}
}

最佳答案

试试这个

public static void main(String[] args)throws IOException {

    Scanner s = new Scanner(System.in);

    int[] numbers = fileToArray();
    Arrays.sort(numbers);
    while(true) {
        System.out.print("Enter a number in the file: ");
        int numb = s.nextInt();

        int i = Arrays.binarySearch(numbers, numb);

        if (i < 0) {
            System.out.print("Number is not in file\n");
        } else if (i >= 0) {
            System.out.print("This number is in the file\n");

        }
    }
}

关于java - 我试图让我的程序继续请求输入并回答该输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333440/

相关文章:

java - 在 Java 中使用正则表达式转义双斜杠

java - Butterknife @generate 不工作{错误 :(23, 6) 错误:找不到符号类绑定(bind)}

java - 将文本文件扫描到对象数组中

arrays - 如何在类图上将属性的数据类型表示为对象数组?

javascript - 如何根据javascript中的值拆分字符串

java - Java 中的 Get 和 set 方法出现问题

java - 为什么 webdriver 打开这么多驱动程序?

java - xe :beanNamePicker, 无法将我的值从注释 View 获取到结果集中

java - super.toString() 或使用属性名称

javascript - 数组元素的赋值是否会复制或引用 JavaScript 中的元素?