各位高手,这是我教材里的一道例题,是根据数据统计上网费用,我对程序中第二个try语句块中的while(true)循环使用感到奇怪,它可是无限的循环,而且在此循环中没有break语句,为什么不用for (int j = 0; j < items.length; j++)呢?难道使用while(true)里面的树组循环到最后都自动退出了吗?好象还有就是二分查找里面也用到了while(true),真的不明白是什么意思?import java.io.*;
public class DataStreamDemo
{
  public static void main(String[] args) throws IOException
  {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("netfee.txt"));
    double[] netfees = {0.30, 0.24, 0.42, 0.87, 1.50, 0.96, 0.69};
    int[] minutes = {10, 8, 13, 29, 50, 32, 23};
    String[] items = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
    for (int i = 0; i < netfees.length; i++)
    {
      dos.writeInt(minutes[i]);
      dos.writeChar('\t');
      dos.writeDouble(netfees[i]);
      dos.writeChar('\n');
    }
    dos.close();    DataInputStream dis = new DataInputStream(new FileInputStream("netfee.txt"));
    double netfee;
    int minute;
    double total = 0.0;
    try
    {
      System.out.println("你的上网费是:");
      int i = 0;
      while(true)                         //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      //for (int j = 0; j < items.length; j++)
      {
        minute = dis.readInt();
        dis.readChar();
        netfee = dis.readDouble();
        dis.readChar();
        System.out.println(items[i] + "\t" + minute + "分钟" + "\t小计¥:" + netfee);
        total = total + netfee;
        i++;
      }
    }
    catch (EOFException e) {}
    System.out.println("总费用:¥" + total);
    dis.close();
  }
}

解决方案 »

  1.   

    while循环表示的程序有条件循环而且必须执行一次
      

  2.   

    那么请你看看这个程序里面的find方法,它里面也有个while(true)循环,那他为什么不抛出异常呢,它是什么退出的,这个程序可以正常编译的public class BinarySearchTest
    {
      private long[] a;
      private int nElems;  public BinarySearchTest(int max)
      {
    a = new long[max];
    nElems = 0;
      }  public int size()
      {
    return nElems;
      }  public int find(long searchKey)
      {
        int lowerBound = 0;
        int upperBound = nElems - 1;
        int curIn;
        while(true)
        {
          curIn = (lowerBound + upperBound) / 1;
          if (a[curIn] == searchKey)
            return curIn;
          else if (lowerBound > upperBound)
            return nElems;
          else
          {
            if (a[curIn] < searchKey)
              lowerBound = curIn + 1;
            else
              upperBound = curIn - 1;
          }
        }
      }
    }
      

  3.   

    while(true) 
            { 
                curIn   =   (lowerBound   +   upperBound)   /   1; 
                if   (a[curIn]   ==   searchKey) 
                    return   curIn; 
                else   if   (lowerBound   >   upperBound) 
                    return   nElems; 
                else 
                { 
                    if   (a[curIn]   <   searchKey) 
                        lowerBound   =   curIn   +   1; 
                    else 
                        upperBound   =   curIn   -   1; 
                } 
    }这么多地方可以退出,你怎么