|
-
October 23rd, 2006, 08:07 PM
#1
Do..While - No termination.
This program asks the user to input
Name
Age
Height
(or press 'q' to quit)
If details are age = 30-40 or height 180-195
Message: +Name is suspect
my problem is that when i type q
the program doesnt terminate
so i guess the problem is at the 'while' statement
can anyone tell me whats wrong?
Thanks
import java.util.*;
public class CrimeInvestigation
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String name;
int age,height;
do
{
System.out.print("Name of suspect (press 'q' to quit): ");
name = sc.next();
System.out.print("Age: ");
age = sc.nextInt();
System.out.print("Height: ");
height = sc.nextInt();
if ((age >= 30 && age <= 40) || (height >= 180 && height <= 195))
{
System.out.print(name+" is a suspect");
}
else
{
System.out.print(name+" is not a suspect");
}
System.out.println("");
System.out.println("");
} while (name != 'q');
}
}
-
October 24th, 2006, 02:07 AM
#2
Re: Do..While - No termination.
Hi,
You can't compare a String with == or with != you need to use the equals method. eg:
Code:
(! name.equals("q"))
Hope This Helps
Byron Tymvios
Please use [ CODE ] and [/ CODE ] tags when posting code! See THIS on how to use code tags.
-
October 24th, 2006, 05:44 AM
#3
Re: Do..While - No termination.
-
October 24th, 2006, 05:52 AM
#4
Re: Do..While - No termination.
Using == on a String compares if the 2 objects you are comparing are the same object, it doesn't compare the actual contents of the String.
Byron Tymvios
Please use [ CODE ] and [/ CODE ] tags when posting code! See THIS on how to use code tags.
-
October 24th, 2006, 05:55 AM
#5
Re: Do..While - No termination.
On a different note:
If you give the user an option to quit the program and they take it then the program should quit, it shouldn't ask them irrelevant questions before quiting. So you really ought to be checking for a 'q' immediately after else when the user enters 'q' to quit the program they will still be asked for the age and height which is irrelevant.
Providing a way to cancel an accidental quit by asking the user if they are sure they want it quit is acceptable and in many situations is good practice.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|