我想设置一个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();
}
答案 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.我也优化了您的代码。