简体   繁体   English

Do Loop变量无法解析为变量

[英]Do Loop variable can't be resolved to a variable

I have this code in which I loop until the user enters a -1. 我在其中循环播放此代码,直到用户输入-1。 However, I get the error : 但是,我得到了错误:

key cannot be resolved to a variable 键不能解析为变量

I have used this code before and I didn't have a problem with it, so I'm not sure why I'm having this problem. 我以前使用过此代码,但没有遇到任何问题,所以我不确定为什么会有这个问题。

System.out.println("\nEnter a number, -1 to stop : ");
do {
  int key = scan.nextInt();
  int result = interpolationSearch(integerArray, key);
  if (result != -1) {
    System.out.println("\n"+ key +" element found at position "+ result);
  }
    break;
} while (key != -1);    // quit 
System.out.println("stop");
}

You need to declare key outside the do loop and can get the nextInt every time the loop runs through. 您需要在do循环外声明key ,并且每次循环运行都可以获取nextInt Also there is no need of break statement in the loop. 同样,循环中也不需要break语句。

System.out.println("\nEnter a number, -1 to stop : ");
int key;
do {
  key = scan.nextInt();
  int result = interpolationSearch(integerArray, key);
  if (result != -1) {
    System.out.println("\n"+ key +" element found at position "+ result);
  }      
} while (key != -1);    // quit 
System.out.println("stop");
}

You need to declare int key outside of your do loop. 您需要在do循环之外声明int键。 Because it is declared inside the loop, the while condition doesn't know about it. 因为它是在循环内声明的,所以while条件不知道它。 This is called being out of scope. 这称为超出范围。 Here are some examples and an explaination of scope http://java.about.com/od/s/g/Scope.htm . 以下是一些示例和有关范围http://java.about.com/od/s/g/Scope.htm的说明

Change it to this: 更改为此:

System.out.println("\nEnter a number, -1 to stop : ");
int key;
do {
  key = scan.nextInt();
  int result = interpolationSearch(integerArray, key);
  if (result != -1) {
    System.out.println("\n"+ key +" element found at position "+ result);
  }
    break;
} while (key != -1);    // quit 
System.out.println("stop");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM