• Post Reply Bookmark Topic Watch Topic
  • New Topic

Boolean if/else with the word yards being true  RSS feed

 
Alberto Beltran
Greenhorn
Posts: 1
Mac OS X Netbeans IDE Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am three weeks into my first Java programming class and have an assignment that is asking us to convert yards to meters and vice versa.
I have the calculation methods and calling of those methods in a different class done but can't figure out how to get the word yards to be true and meters to be false.
If I type true or false I can get to the if or else respectively but not when typing the words in the prompts.

Any help would be greatly appreciated.

 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.
In future, while posting code, please UseCodeTags. I have added them to your post. As you can see, it makes the code easier to read and understand.

It's ages since I coded with command line input, so I might be off.

First you ask the user to type "yards" or "meters"

Then you try to take it as a boolean!

Then you have this

You are ignoring your user input!!!(provided you fixed the Boolean x issue!


 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good points have already been made, but to add to those:

You ask the user to input either "yards" or "meters" and then you attempt to store that input into a boolean type which is either true or false. What will the value of your boolean variable, x, be?

Is it best to store the user's input in a boolean type variable, or should it be a String? If you store the user's input in a String, you could then test for the input in your if statement: if ( x.equals( "yards" ) ) . . .

Or could you give the user different instructions? E.g., "Enter true if converting yards to meters, false if converting meters to yards."

As it is, your if( true ) statement will always execute.
 
Shelley Programmer
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) The user is typing a string (a word, yes?), so you would want to get the user's input as a string. Booleans can ONLY be true or false. "yards" is a String.
2) You can use the .equals() method to test if the string is yards or meters.
3) if(true) - well, the if statement tests the thing inside of the parentheses, which is true.
Since true is always true, your if statement will always execute.
if you want to see if x is true, you would say this:
if(x)

x is either true or false. If it's true, then the statement is executed. Otherwise, the statement is not executed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!