2012-03-23 141 views
0

请谁可以帮我这个节目从扫描仪转换为JOptionPane的的Java:转换扫描仪与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"); 

       } 
      } 
+1

想指出的:它是拼写“元素” – 2012-03-23 15:05:35

+0

你的意思是当你说“转换为JOptionPane的”你希望从它接收到的输入? – 2012-03-23 15:07:11

+0

问题正确吗?你想将Scanner类转换为JOptionPane? – ChadNC 2012-03-23 15:07:53

回答

1

这里有一个建议:

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

,你可以使用LIK E本:

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"); 

} 
+0

我看不懂,也没有工作 – Almutasim 2012-03-23 17:09:35

+0

你不明白什么? – aioobe 2012-03-26 18:53:03