Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
How can I adapt this program so that the user would be given another go irrespective of whether or not an upper case or lower case 'y' is entered?
I have read the 'Taking Control' chapter countless times, and I'm no closer to a solution. I'm sure It's something simple though.
/* program prompts user for two numbers, adds them together, and runs
until user chooses to quit */
public class Chapter3Arithmetic
{
public static void main(String[] args)
{
int num1, num2;
char choice;
do
{
System.out.print("Enter a number: ");
num1 = EasyIn.getInt();
System.out.print("Enter another number: ");
num2 = EasyIn.getInt();
System.out.println("The sum of the two numbers is "
+ (num1 + num2));
System.out.print("Do you want another go (y/n): ");
choice = EasyIn.getChar();
}
while(choice == 'y');
}
}

Don't do JAVA.
Either convert choice to lower case and test 'y' or test for both
Very good, thinking about user input possibilities.

thanks. that's exactly what i can't figure out? how can i test for both conditions, as well as other possible errors such as numerical input? which construct will work best?

switch (choice.toLowerCase())
{
case 'y':
//yes
break;case 'n':
//no
break;default:
//Invalid input
break;
}Dunno if java uses ?: , but if it does, this could also be written as
(choice.toLowerCase() == 'y')?(/*yes*/):(/*any other input*/)AKhalifman@hotmail.com

Oh, sorry, didn't read the question; if you want to keep the code the way it is, simply use the toLowerCase() String method.
AKhalifman@hotmail.com

i'm a java newebie (like you didn't guess). i'm sure there's a simple solution to the problem that doesn't involve using a pre-defined java class?
can this be achieved using an if, if...else, or switch statement, for example?
i'm working my through 'JAVA in two semesters', but the solutions are only available to lecturers. hmmm :/ v frustrating.

bah. I just noticed that you used a char, not a String.
I just started Java (although I've been programming in C++ for a while), but I don't think there's a way to directly edit chars at a low level (as there is in C++).
In C++, you'd use the tolower() function; I don't know if there is an equivalent method in Java.AKhalifman@hotmail.com

while(choice == 'y' || choice == 'Y');
I don't do Java much, but in C/C++ OR is ||. I believe that it is also in Java, but it could be the word 'or', as in:
while (choice == 'y' or choice == 'Y');
I wouldn't worry about numeric input, because any input will be accepted as a character. So if they type '1', it will be the same as typing 'n', 'q', 'x', etc. The loop test will fail, thus the loop will stop.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |