请谁能帮助我将该程序从Scanner转换为JOptionPane

当我开始convert依时,我发现了一些困难

“此代码用于二进制搜索”

import java.util.Scanner;
public class bs {
        public static void main(String [] args){
         int []a = new int[100];
         int x,low,high,mid,i,n;
            Scanner scan  = new Scanner (System.in);
            System.out.println(" Enter the n element");
            n = scan.nextInt();
            System.out.println("Enter " + n +  " elements");
            for (i=0;i<n;i++)
            a[i] = scan.nextInt();
            System.out.println(" enter the search element");
                x = scan.nextInt();
                low = 0; high = n-1;
                 while ( low <=high){
                 mid  = (low + high)/2;
                 if (x ==a[mid]){
             System.out.println(" Element is found at location"  + mid)   ;

        return;
        }
                 else if (x<a[mid])
             high = mid-1;
                 else
                 low  = mid+1;

         }
               System.out.println(" element is not found");

               }
            }

最佳答案

这是一个建议:

public static int getInt(String msg) {
    // TODO: Error checking.
    return Integer.parseInt(JOptionPane.showInputDialog(msg));
}


您可以这样使用:

public static void main(String[] args) {
    int[] a = new int[100];
    int x, low, high, mid, i, n;

    n = getInt("Enter the n element");

    for (i = 0; i < n; i++)
        a[i] = getInt("Enter element " + (i+1));

    x = getInt(" enter the search element");

    low = 0;
    high = n - 1;
    while (low <= high) {
        mid = (low + high) / 2;
        if (x == a[mid]) {
            System.out.println(" Element is found at location" + mid);

            return;
        } else if (x < a[mid])
            high = mid - 1;
        else
            low = mid + 1;

    }
    System.out.println(" element is not found");

}

07-27 13:49