When I run my code, it gives me an error that says, "Syntax error on token "{", throw expected after this token." The error is on line 7's code.
class WhileLoopTest {
public static void main(String[] args){
apple = 0;
while (apple = 0) {
(int)(Math.random( )*(60) + 5);
return;
}
}
}
on the line while (apple = 0) you are setting the variable instead of declaring it. The while loop expects that you pass it a boolean. You are probably trying to use the comparison equals ==. The full line should read while (apple == 0).
First , you need to define a type for your variable apple because Java is statically type
apple = 0;
Read more About Statically typed vs Dynamically typed
change to
int apple = 0;
Second, (int)(Math.random( )*(60) + 5); is not statement so you need to either print the value or return it
Third, while (apple = 0) { is wrong because compiler looking for Boolean expression
while(Boolean_expression)
{
//Statements
}
change to while (apple == 0 ) {
You need to add an extra equals sign to the condition within the while statement (at the moment you are assigning the value of 0 to apple, instead of texting if it is equal), so it looks like this
while(apple == 0){
Pleas note that the while loop has no function at all, since you are returning within the loop. This will stop your program execution as you are returning from the main method. The computation of a random number doesn't serve a purpose here as you aren't assigning a variable to it or printing it.
Also, you are not defining a type for the apple variable. Try making it of type int.
int apple = 0;
I suggest that you look up some tutorials on java as you seem to misunderstand several concepts within the language.
Related
public boolean replaceEventAt(String eventStr, int position){
boolean answer = false;
if((position > 0) && (position <= events.size())){
events.get(position - 1) = eventStr;
answer = true;
}
return answer;
}
Error on fifth line where Java complains that position is a value not a variable please help
An assignment operates between what is known as an lvalue and an rvalue.
lvalue stands for left-hand-side-value.
rvalue stands for right-hand-side-value.
The rvalue can be many things, like a variable, a constant, a function call expression, etc, but the left side must be assignable, so it cannot be a constant or a function call.
In your case, your rvalue is a function invocation; that won't work. The compiler error message is saying exactly that.
If we knew what you are trying to do we could perhaps explain more, but it is unclear from the code that you posted that it is that you want to accomplish. Perhaps events is some collection, and you want to set the element at position position - 1 to eventStr, in this case you would probably want events.set( position - 1, eventStr );
Left hand side must be a variable (ie we should be able to assign a value to it ). But in your case it is performing a get operation So it is throwing an Error
As you are trying to replace using index I assume events is object of List interface.
In this case below code should work as per your requirement.
public boolean replaceEventAt(String eventStr, int position){
boolean answer = false;
if((position > 0) && (position <= events.size())){
events.set(position - 1, eventStr);
answer = true;
}
return answer;
}
I don't understand why I get a compile error. In my view, this method first evaluates whether n is > 0. When this is the case, then "good" will be assigned to the String object local. However, if this is not the case, then it will not do anything. Next, the method enters another decision construct. This time, it evaluates whether n <= 0. If so, it will assign "bad" to the String object.
In any of both cases, local should be initialized. However, I get a compile error, and the compiler says it may not be initialized. I do not understand where this is coming from.
Note that I know how to correct the second if by replacing it with else and removing the boolean condition. I just don't understand why in a syntax sense this is incorrect.
public class Donkey{
String s1 = "green";
public void generateReport(int n){
String local;
if(n > 0)
local = "good";
if(n <= 0)
local = "bad";
System.out.println(local);
}
The compiler has no way to 'know' that you've handled all the cases with your if statements.
Consider this example (note that the second if is just less than):
String local;
if(n > 0)
local = "good";
if(n < 0)
local = "bad";
If n = 0, then local will not get defined.
The compiler doesn't test your if statements to see if they handle all the cases while compiling.
Changing it to if/else will fix the error as you mentioned. You can also initialize the variable as other users have pointed out.
The problem is that if n is not greater than 0 and is not less or equal than 0 the var local is not initialized. So that is what the compiler is telling you.
You can solve this by initializing the local var with something.
String local = "";
The problem is solved when you use else because for the compiler there can be only 2 possible states, the one if the condition is true and the other if is not, there is no possible third state because the else contemplates all.
i was trying to write some C++ codes into java, now i have writter following code into java but it is throwing errors!
if(ShapeNotFound && xd*yd - nPixel[k] < xd+yd) // Condition for RECTANGLE
{
System.out.print("\n "+in+" \t Rectangle \n");
fileWriter3.write("\n "+in+" \t Rectangle \n");
Shape[k] = 2;
ShapeNotFound = 0;
}
I am getting following error :
The operator && is undefined for the argument type(s) int, boolean
Please help, tell me how to write the above if condition correctly in java
C and C++ both assume that for integers 0 is false and all other values are true.
Java does not make the same assumption so you need to add a check for int!=0 into the expression i.e.:
if((ShapeNotFound!=0) && (xd*yd - nPixel[k] < xd+yd))
Or alternatively your ShapeNotFound variable should be of type boolean not int.
It would be worth converting variable names etc to Java style guidelines as well.
Java can not convert int into boolean automatically.
It looks like ShapeNotFound is an integer, but you're implicitly treating it like a boolean (true or false). Java only likes genuinely boolean expressions, so you'll need to change the condition to something like this:
if (ShapeNotFound != 0 && xd*yd - nPixel[k] < xd+yd)
For readability, I'd suggest putting some brackets round each part of the condition. That's an issue of personal preference though.
This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber
I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.