Why does this code cause an “illegal start of expression” exception?
-
06-09-2019 - |
Question
These are my questions:
I'm getting a couple of errors on the line "public static boolean validNumCheck(String num){" - "illegal start of expression", "';' expected", and "')' expected".
How can I give the user 3 tries in total for each number? I believe right now the programme asks the user for 3 numbers and gives them 3 tries in total to get the numbers correct (My explanations suck... read the code to get a better idea of what I mean).
This is my code:
import javax.swing.JOptionPane;
public class Assignment3 {
public static void main (String[] args){
final int MAX_TRIES = 3;
int[] attempts= new int[2];
String[] getNumber= new String [2];
//Ask the user for 3 integers.
while(attempts[0]<MAX_TRIES){
getNumber[0]= JOptionPane.showInputDialog(null,"Please enter an integer between 0-200.");
//Pass the value to validNumChek
validNumCheck (getNumber);
//If it is not a valid number give the user 3 more tries.
if (getNumber== false){
while(attempts[1]<MAX_TRIES){
getNumber[1]= JOptionPane.showInputDialog(null,"Please enter an integer between 0-200.");
attempts[1]++;}
}
attempts[0]++;
}
//Parse the string to an integer and check if it is a valid number.
public static boolean validNumCheck(String num){
int number;
try {
number = Integer.parseInt(num);
return number >= 0 && number <= 200;
}catch(NumberFormatException e){
//If it is not a valid number return false.
return false;
}
}
}
Solution
I think it is important to create a pseudo code or algorithm of the problem first and then if it works deal with the programming later. Otherwise you'll be solving two things at the same time 1. Problem logic and 2. Implementation details.
This is how I would do it.
//The three numbers should be entered by a user in the main method.
MAIN PROGRAM starts
declare a , b , c as numbers
//The numbers should be positive and less than 200.
// see validNumCheck below.
//part 1.If not, the program asks the user to renter the number.
//part 2.The user will have three chances to enter a valid number for each number.
//part 3. If the number is still invalid after the three trials, the program displays an error message to the user and ends.
// ok then read a number and validate it.
attempts = 0;
maxAttempts = 3;
//part 2. three chances... .
loop_while ( attemtps < maxAttempts ) do // or 3 directly.
number = readUserInput(); // part 1. reenter the number...
if( numcheck( number ) == false ) then
attempts = attempts + 1;
// one failure.. try again.
else
break the loop.
end
end
// part 3:. out of the loop.
// either because the attempts where exhausted
// or because the user input was correct.
if( attempts == maxAttemtps ) then
displayError("The input is invalid due to ... ")
die();
else
a = number
end
// Now I have to repeat this for the other two numbers, b and c.
// see the notes below...
MAIN PROGRAM ENDS
And this would be the function to "validNumCheck"
// You are encouraged to write a separate method for this part of program – for example: validNumCheck
bool validNumCheck( num ) begin
if( num < 0 and num > 200 ) then
// invalid number
return false;
else
return true;
end
end
So, we have got to a point where a number "a" could be validated but we need to do the same for "b" and "c"
Instead of "copy/paste" your code, and complicate your life trying to tweak the code to fit the needs you can create a function and delegate that work to the new function.
So the new pseudo code will be like this:
MAIN PROGRAM STARTS
declare a , b , c as numbers
a = giveMeValidUserInput();
b = giveMeValidUserInput();
c = giveMeValidUserInput();
print( a, b , c )
MAIN PROGRAM ENDS
And move the logic to the new function ( or method )
The function giveMeValidUserInput would be like this ( notice it is almost identical to the first pseudo code )
function giveMeValidUserInput() starts
maxAttempts = 3;
attempts = 0;
loop_while ( attemtps < maxAttempts ) do // or 3 directly.
number = readUserInput();
if( numcheck( number ) == false ) then
attempts = attempts + 1;
// one failure.. try again.
else
return number
end
end
// out of the loop.
// if we reach this line is because the attempts were exhausted.
displayError("The input is invalid due to ... ")
function ends
The validNumCheck doesn't change.
Passing from that do code will be somehow straightforward. Because you have already understand what you want to do ( analysis ) , and how you want to do it ( design ).
Of course, this would be easier with experience.
Summary
The steps to pass from problem to code are:
Read the problem and understand it ( of course ) .
Identify possible "functions" and variables.
Write how would I do it step by step ( algorithm )
Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.
OTHER TIPS
This thread may be helpful. Those are hints to pass from "problem description" to "actual coding"
As per your specific questions:
How can I give the user three chances to enter a valid number for EACH number? (I don't want the 'answer' just some ideas/hints.
How would you do that if you were a cashier ( with bad memory ) in real life? And I mean very very bad memory, so much that you cannot remember if you're rejecting a customer for first time or second?
I would write it down in a piece of paper, and each time I reject the customer I add a "|"
"| | |"
When the paper has three lines in it I would call the police. .. :)
That's similar here. If you don't have some thing that may vary you will get in a infinite loop ;)
Is validNumCheck suppose to return a value AND THEN exit in the void main method
No
...or can I have it just exit the programme in that main method?
Yes.
When you count ( in real life ) you don't need to store the numbers in boxes, you just have to change the value of the count and have a limit.
For instance you can replace this:
int[] count= new int[2];
With this:
int attemtps = 0 ; // or count
int maxTries = 3;
You cannot assign an array of integers to an arrays of Strings.
String[] getNumber= new int [2];
Using an array of Strings may work, but you have to assign an array of strings
String[] numbers = new String[2];
Or you can use and array of int:
int [] numbers = new int [2];
Pick one.
Remember arrays are like boxes where you can store values.
In the method signature (that would be "public static int validNumCheck(num1,num2,num3)
"), you have to declare the types of the formal parameters. "public static int validNumCheck(int num1, int num2, int num3)
" should do the trick.
However, a better design would be to make validNumCheck
take only one parameter, and then you would call it with each of the three numbers.
My next suggestion (having seen your updated code) is that you get a decent IDE. I just loaded it up in NetBeans and found a number of errors. In particular, the "illegal start of expression" is because you forgot a }
in the while loop, which an IDE would have flagged immediately. After you get past "Hello world", Notepad just doesn't cut it anymore.
I'm not going to list the corrections for every error, but keep in mind that int[]
, int
, String[]
, and String
are all different. You seem to be using them interchangeably (probably due to the amount of changes you've done to your code). Again, an IDE would flag all of these problems.
Responding to your newest code (revision 12): You're getting closer. You seem to have used MAX_TRIES
for two distinct purposes: the three numbers to enter, and the three chances for each number. While these two numbers are the same, it's better not to use the same constant for both. NUM_INPUTS
and MAX_TRIES
are what I would call them.
And you still haven't added the missing }
for the while loop.
The next thing to do after fixing those would be to look at if (getNumber == false)
.
getNumber
is a String[]
, so this comparison is illegal. You should be getting the return value of validNumCheck
into a variable, like:
boolean isValidNum = validNumCheck(getNumber[0]);
And also, there's no reason for getNumber
to be an array. You only need one String
at a time, right?
Every parameter in a method definition needs a type:
public static int validNumCheck(int num1, int num2, int num3){
but I wonder why you pass all three numbers in, when you only check one at the time. And you want to return if the number is true or not, so the return value should be an boolean:
public static boolean validNumCheck(int num){
// test and return true or false
Also, if the user enters "abc", you will get an exception from the "Intger.pareInt(String)" method. Maybe you want to store the entered text as a String an give it to validNumCheck, try to convert it and check if it is between 0 and 200.
public static boolean isValidNumber(String num){
try {
int number = Integer.parseInt(num);
return number >= 0 && number <= 200;
}catch(NumberFormatException e){
return false;
}
}
EDIT 1: For the three tries, you need a loop, that runs till the number is valid or three tries are taken. Simply count the tries with in int.
By the way, are you sure you have to use JOptionPane and JMessageDialog? This is GUI stuff and just complicates that hole thing. You also could read and write text to the console by using System.out and System.in
EDIT 2: One more tip, when you create an int array with a given length, every place in the array is filled with 0, so you could write:
int[] count= new int [3];
and don't need that:
count[0]=0;
count[1]=0;
count[2]=0;
And if you want to use other values than 0, you could use a shorter form like this:
int[] count = {1, 5, 2}
EDIT 3: One thing you should do/learn is this: don't write the whole thing and end up with many errors and a not running program. Code a little, test a little. Do one part of it, see it run and you are happy.
Did this thing ever run? I mean, did you already saw that JOptionPane-InputDialog you try to use? If not, do only this first: (and run it!)
public class Assignment3 {
public static void main (String[] args){
int[] numbers = new int[3];
for (int i = 0; i < numbers.length; i++) {
JOptionPane.showInputDialog("enter something");
}
}
}
Got it to run? Great! Now, try to wrap that line with the JOptionPane in a loop, that runs till the user entered a valid number (using the checkValidNum method you already got) or used his three attempts.