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
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World
The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}
Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}
This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}
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.
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:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am newbie in java but I think I have done well teaching myself in these few weeks. But now I am stuck at this loop.
Here is a method from one of my class. To help me debug, I have added "myString" string and "syntax" list inside this method to demonstrate what is happening and to keep it simple, at least for now.
public void getIndex(){
String myString = "2 2 + 3 5";
String[] syntax = myString.split(" ");
for (int index = 0; index < syntax.length; index++){
System.out.println("current index is: " + index);
System.out.println("It has: " + syntax[index]);
// these print statements are made to help me debug
if (syntax[index] == "+"){
indexNeeded = index;
break;
}
}
System.out.println("Index Needed: " + indexNeeded);
As you can see inside the loop, I want to break the "for loop" when the element of the list, "syntax" is "+".
(I am showing "+" here but it can be anything in the actual program.)
Here is the output, when run this method:
current index is: 0
It has: 2
current index is: 1
It has: 2
current index is: 2
It has: +
current index is: 3
It has: 3
current index is: 4
It has: 5
Index Needed: 0
The loop should have stopped when it found "+" but it seems that "if statement" is not working at all, and hence "indexNeeded" hasn't changed.
It's a simple method but what am I doing wrong here?
You're trying to compare strings with ==. That doesn't work, you need to use .equals():
change:
syntax[index] == "+"
to
syntax[index].equals("+")
== only returns true when both objects refer to the same instance. equals() will return true when the contents of the string are the same. This is what you want.
Replace
if (syntax[index] == "+"){
with
if (syntax[index].equals("+")){
When you are trying == it comparing the references and syntex[index] is not referring to same location where literal "+" is. So they are not equal.
// If syntax[index] get '+' value from somewhere but not literal
if(syntax[index] == "+" ) // is false
// right way is
if(syntax[index].equals("+")) // is true
// If syntax[index] get '+' value from literal
syntax[index] = "+";
if(syntax[index] == "+" ) // is true
// This approach is faster but has mentioned above has limitations.
When you do equals it actually compares the content.
You should write:
syntax[index].equals("+")
"+" is a reference to a String, and syntax[index] is another. But here you want to compare the objects themselves, not their references.
If you take two objects a and b of whatever class, a == b will test that the references are the same. Testing that they are "the same" is written a.equals(b).
You should read Java's .equals() documentation carefully, it is a fundamental part to understand.
for String, you need to do
syntax[index].equals("+")
If you want to compare the value of a String you need to use .equals() but if you want to compare references you use the operator ==. That a common mistake with newbies.
Take a minute and see the difference between:
syntax[index] == "+"
and
"+".equals(syntax[index])
it that order you don't allow possible null pointer in syntax[index]
Here's a fun, educational way to fix your problem. Add a call to String.intern() to your method and it will work fine. Amaze your friends! :)
public int getIndex()
{
String myString = "2 2 + 3 5";
String[] syntax = myString.split(" ");
int indexNeeded = -1;
for (int index = 0; index < syntax.length; index++)
{
System.out.println("current index is: " + index);
System.out.println("It has: " + syntax[index]);
// these print statements are made to help me debug
if (syntax[index].intern() == "+")
{
indexNeeded = index;
break;
}
}
return indexNeeded;
}
Note that it is better to return a value from a method than it is to use variables with class scope. Class-scoped variables should be reserved for data that can be considered a property of the object. indexNeeded doesn't meet that description, and it's a poor name for an int - it sounds like it should be a boolean.
Equality checks in Java come in two forms.
The equality operator "==" checks to see if two variables refer to the same object. In your case, this test fails because, though their content is the same, you're referring to two different string objects.
The .equals() method is available on every Java object and provides extensible equality checking. In the case of Strings, consider the following:
"+".equals("+") // evaluates to true
going back to the equality operator:
"+" == "+" // evaluates to false
See this page for more detail.
Use return; instead of break;
it works for me
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.