Java:如果另一个int尚不存在,则定义int

时间:2013-07-08 15:18:14

标签: java loops if-statement while-loop int

我想设置一个int old int new的值,但在第一个while循环中int old必须在int new之前定义,这意味着int new尚不存在。因此int old无法获得int new的值。

如何在第一个循环中提取此案例并定义int old = 0(例如)。我没有找到合适的函数,因为每个带有int new的if循环都会抛出异常,因为int new不存在。我怎么处理这个?

    while(true) {
        try {
            int iold = inew;
            int inew = input.read();

            if (inew!=-1 && iold != -1) {
              text = tf.getText();
              tf.setText(text+(char)inew);
            }
            if (inew != -1 && iold = -1) {
             text = tf.getText();
             tf.setText(""+(char)inew);
            }
            Thread.sleep(100);
         } catch(Exception x) {
              x.printStackTrace();
         }
         repaint();    
    }

3 个答案:

答案 0 :(得分:1)

将int old声明为您的成员变量或while循环之前。

int old = 0;
while(condition){
   // your codes
}

答案 1 :(得分:1)

简单地做

    int inew = 0; //Or any default value
    while(true){
      try{

        int iold=inew;

        inew=input.read();

        if (inew!=-1 && iold!=-1)
        {
          text=tf.getText();
          tf.setText(text+(char)inew);
        }
        if (inew!=-1 && iold=-1)
        {
          text=tf.getText();
          tf.setText(""+(char)inew);
        }

        Thread.sleep(100);
      }
      catch(Exception x){
          x.printStackTrace();
      }

      repaint();    
    }

答案 2 :(得分:0)

只需在int inew = 0子句之外声明while,就像这样:

int inew = 0;
while(true)
{
  try{

    int iold=inew;

    inew=input.read();

    if (inew != -1) {
        text = tf.getText();
        if(iold != -1) {
            tf.setText(text+(char)inew);
        }
        else {
            tf.setText(""+(char)inew);
        }
    }
    Thread.sleep(100);
  }
  catch(Exception x){x.printStackTrace();}
  repaint();    
}

第一个循环,iold将获得值0.我也优化了您的代码。