char answer = input.next().charAt(0);
for (int i =1 ;i!=0 ; ) {
int j = 0 ;
if ( answer=='*' || answer=='/' || answer=='+' || answer=='-') {
i= 0 ;
}
else
{
i=1;
while ( j<i) {
System.out.println( " please reenter the operation ") ;
//answer=input.next().charAt(0) ;
j++ ;
}
}
}
在这段代码中,我在循环外声明了变量answer来运行代码但是在我的主代码中,我试图将变量放入循环中比如这里的
for (int i =1 ;i!=0 ; ) {
char answer = input.next().charAt(0) ;
}
.......
所以循环外的变量不能被使用
我会遵循这样的模式:
char answer;
boolean invalid;
do {
System.out.print("Operation: ");
answer = input.nextLine().charAt(0);
invalid = (answer != '*' && answer != '/' && answer != '+' && answer != '-');
if (invalid) {
System.out.println("Invalid operation. Please re-enter!");
}
} while (invalid);
// ... do something with "answer" here ...