请谁能帮我将此程序从 Scanner 转换为 JOptionPane
当我开始转换时,我发现了一些困难
“此代码用于二分查找”
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");
}
关于Java:从 Scanner 转换为 JOptionPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9841508/