Quote:
Originally Posted by kewlgeye
I have some code here that I am having a really difficult time figuring out what I have done or am still doing wrong. I am trying to type this code for my class, and the code is suppose to allow a user to enter a number 1-4 and say Congratulations you have entered "number" or you have entered an invalid number.
However, it is also suppose to allow the user to enter a letter a-e and give a similar response. This is what I have coded so far, I have learned to use a scanner console = new scanner(system.in); statement
and I used this in another attempt to figure this out but I still am having a difficult time comparing the a-e statements and I don't know why.
I have been speaking with my colleagues and they tell me that I should try this simple approach using string methods and scanner.next methods, but I have read in my book and don't understand what I am doing still. Unfortunatelt my school is online and I don't have anyone to verbally speak too about this. Here it is.
// user to enter a number between 1-4 OR the letters a-e //
import javax.swing.JOptionPane;
public class Entering_A_Number
{
public static void main(String[] args)
{
int number;
String numString;
numString = JOptionPane.showInputDialog("Enter a number or letter:");
number = Integer.parseInt(numString);
if (number < 5)
System.out.println("Congratulations you entered " + number);
if (number > 0)
System.out.println("Congratulations you entered " + number);
else
System.out.println("Sorry you entered an invalid number " + number);
if (number == 'a') || (number == b) || (number == c) || (number == d) || (number == e)
System.out.println("Congratulations you entered " + number);
else
System.out.println("Sorry you entered an invalid letter " + number);
System.exit(0);
}
}
|
I have found that this is working for me, but now I am continuiing to get the error that I have entered an invalid key, this is my message, so I am happy that I am at least seeing it, but the problem is when I type the 1 in their it tells me its not a valid key when it should be??? Whats wrong with this?
import java.util.*;
public class Entering_A_Number
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Please enter a number or a letter: ");
String number = console.next();
if (number == "1")
System.out.println("Congratulations you entered " + number);
else
System.out.println("Sorry you entered an invalid key " + number);
System.exit(0);
}
}