![]() |
[Java] So here I am having another problem.
Like before, I'm still a beginner, so kinda keep this simple if possible please. This time I am writing a program where the user inputs an integer and the program decides whether it is even or odd. I know the exact algorithms because I wrote this program 2 years ago in Visual Basic. the section where the 'if statements' are located keeps getting an error when i compile the file. It says the variables are integers and need to be booleans, but when I switch them i get the exact opposite reaction. How can i fix this for the desired output?
// Java Programming Assignment 2.3 // Program used to determine if an integer is even or odd import javax.swing.JOptionPane; // uses JOptionPane public class EvenOdd { // main method begins execution of Java application public static void main( String args[] ) { String input; // string entered by user String output; // string containing result output = ""; int number; // integer entered int number2; boolean numResult; // result calculator // read integer as String input = JOptionPane.showInputDialog( null, "Enter any integer.", "INPUT", JOptionPane.QUESTION_MESSAGE ); // convert integer from String to int number = Integer.parseInt( input ); number2 = number % 2; if ( number2 = 1 ) numResult = false; if ( number2 = 0 ) numResult = true; // determine if even or odd if ( numResult = true ) output = "Odd."; if ( numResult = false ) output = "Even."; // display output JOptionPane.showMessageDialog( null, "The integer you selected is " + output, "RESULT", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end method main } // end class EvenOdd |
You need two equals signs to do a comparison. For example: if (numResult == true)
Otherwise it just sets the variable equal and doesn't return the result of the comparison. And where you have statements like if ( number2 = 0 ), you need if ( number2 == 0 ) instead. *edit* Since numResult is a boolean variable already, you don't need to use "==true" You can just use "if (numResult)". The way the if statement works, it just looks for a true or false result within the parentheses. You don't really need to compare a boolean variable to anything since it already contains a true or false value. If you had an integer value, on the other hand, you need two equals signs to do a comparison. |
Alright, thanks spectre. That fixed it right up.
|
All times are GMT -8. The time now is 11:49 PM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project