0

我是java新手,我有while条件,它工作得很好,但我需要使用for循环:this while条件循环

String command = "";
while ((command = br.readLine())!=null && !command.isEmpty()) {
  int b=0; 
  thisObj.perintah(b,command);
}

我试过用 for 写,我认为类似这样,但它不起作用

for (int b=0;b<command;b++)
   {
   String command = br.readLine();
   thisObj.perintah(b,command);
   }

有谁知道我错过了什么

4

3 回答 3

1

表示为 for 循环的 while 循环:

int b = 0;
for (String command = br.readLine(); command !=null && !command.isEmpty(); command = br.readLine()) {
  thisObj.perintah(b++, command);
}

使用变量名command会使for行很长,所以这里是相同的代码,变量名更短,这样会更清楚发生了什么:

int b = 0;
for (String s = br.readLine(); s !=null && !s.isEmpty(); s = br.readLine()) {
  thisObj.perintah(b++, s);
}
于 2013-10-09T15:06:28.507 回答
0

没有一些帮助, Java 无法与之相比intString您需要将命令转换为数字。试试Integer.parseInt()

但是你不能在for循环的条件下这样做。试试这个:

int b = 0;
String command = "";
while ((command = br.readLine())!=null && !command.isEmpty()) {
  int commandAsInt = Integer.parseInt(command);
  if(b >= commandAsInt) break; // exit the loop

  thisObj.perintah(b,command);
  b++;
}
于 2013-10-09T15:07:42.443 回答
0

目前尚不清楚应该b取什么值。无论哪种方式,您都必须将字符串转换为整数。

String command = "";
for(int b  = 0; (command = br.readLine())!=null && !command.isEmpty(); ++b) {
    thisObj.perintah(b,command);
    String command = br.readLine();
}
于 2013-10-09T15:06:14.320 回答