So this is an odd one, I know the code itself is fairly useless, but what I'm wondering why I get the error:
I was writing some code, I had written this:
if(scan.hasNextInt())
int row = scan.nextInt();
Wasn't thinking about variable scope at the time, obviously this is useless because I can't use row
past the if
anyway. What I don't get is why I got the error I did:
> javac hw.java
hw.java:25: '.class' expected
int row = scan.nextInt();
^
hw.java:25: not a statement
int row = scan.nextInt();
^
hw.java:25: illegal start of expression
int row = scan.nextInt();
^
hw.java:25: ';' expected
int row = scan.nextInt();
^
Now if I just modify that if check to:
if(scan.hasNextInt()) {
int row = scan.nextInt();
}
It will compile fine. I was under the impression that if there was 1 line under the if
the curly brackets were optional... clearly there are other considerations as well or both would either compile or fail.
Could someone explain to me, or point me to a document that explains why I can't declare a local variable under the if
conditional without the curly brackets?
EDIT: Here's the full function:
public static char getinput() {
System.out.println("Where do you want to go? (row column)");
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt())
int row = scan.nextInt();
String input = scan.next();
System.out.println(input);
return 'a';
}