Java If Statement help for beginner - java

I'm just learning java so this is probaly a really dumb question but i can't find a simple enough answer. I'm trying to make a make the program so if the user types "male" to run the System.out.print("You are a guy");
Here's my code:
import java.util.Scanner;
public class clac {
public static void main(String[] args){
double gender;
Scanner input = new Scanner(System.in);
System.out.print("Are you male or female? ");
gender = input.nextDouble();
if (gender == "male"){
System.out.println("You are a guy");
}else{
System.out.print("You are a gal.");
}
}
}

What you are doing wrong: You need to read a String. A String is a piece of text. A double is a decimal number. You are reading a double.
How to solve it:
String gender = input.next(); // read a String, instead of double
if (gender.equals("male")) // if (gender == "male") use .equals for strings
{
System.out.println("U mad bro!?");
} else
{
System.out.println("Hey Doll!");
}

You shouldn't be using nextDouble(), that refers to a decimal.

Try
String gender = input.nextString();
if ("male".equals(gender)){
System.out.println("Wazzup dude?");
}else{
System.out.print("Hey Doll!");
}

I believe you want to use the .next() method for scanner. Try something like this:
import java.util.Scanner;
public class clac {
public static void main(String[] args){
//Define gender variable as a string since that's what we're expecting as an input
string gender;
//Instantiate a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user a question
System.out.print("Are you male or female? ");
//Read in the response into the gender variable
gender = input.next();
//Check to see if the user's answer matches "male"
//We put "male" first in case the user returns a null value
//This will help avoid a fatal error
if ("male".equals(gender)){
System.out.println("You are a guy");
}
else {
System.out.print("You are a gal.");
}
}
}
I hope this helps.

you should use the equals method to compare the two strings,the string is a object,this is a reference,the equals() method will compare the content of two strings,but the == will compare the address of two strings
so,you should write like this:
gender = input.next();
if (gender.equals("male")){
System.out.println("You are a guy");
}else{
System.out.print("You are a gal.");
}

Related

When user presses "enter" key or space enter then error message pops up

I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".

JUnit Testcase not executing properly

I am trying to execute a simple testcase using JUnit, but the testcase always passes even in false condition. I am not able to figure out the mistake in my program below. It looks like somewhere there is a mistake with the Scanner class multiple inputs.
I would like to test with multiple inputs to the testcase such that the test case accepts different employee types.
import java.util.Scanner;
import static org.junit.Assert.assertEquals;
public class EmployeeIdentificationTest extends TestCase {
String firstName, middleName,lastName;
int age=0;
String choice=null;
// assigning the values
protected void setUp(){
do{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter firstName ");
firstName= scanner.nextLine();
System.out.println("Enter middleName");
middleName= scanner.nextLine();
System.out.println("Enter lastName");
lastName= scanner.nextLine();
System.out.println("Enter the age");
int flag=0;
while(flag==0){
try{
age= scanner.nextInt();
flag=1;
}
catch(Exception e){
scanner.nextLine();
System.out.println("Wrong entry, please enter digits only:");
}
}
System.out.println("Do you like to fetch more records press Yes or No");
scanner.nextLine();
choice=scanner.nextLine();
}while(choice.contains("Y")||choice.contains("y"));
}
// test method
public void testEmployee(){
String employeeType=EmployeeIdentification.getEmployeeType(firstName, middleName, powerTrain, age);
if(employeeType.equals("Junior Developer")||employeeType.equals("Senior Developer")||employeeType.equals("System Analyst")||employeeType.equals("Manager")||employeeType.equals("Delivery Head"))
assert(true);
}
}
Valid points from Ldvg, I think what you mean to write is:
public void testEmployee(){
String employeeType = EmployeeIdentification.getEmployeeType(firstName, middleName, powerTrain, age);
if(employeeType.equals("Junior Developer")||
employeeType.equals("Senior Developer")||
employeeType.equals("System Analyst")||
employeeType.equals("Manager")||
employeeType.equals("Delivery Head")) {
assert(true);
} else {
assert(false);
}
}
assert(true);
This line will always return true. The assert keyword will evaluate the expression given after it. You have to assert that the employeeType that the user selected is one of which you accept(i guess you keep them in a list).
A usecase for assert could look like this:
assert(a+b == c);
if you wish to verify that the result of a+b is equal to c.
JUnit checks for various asserts to pass/fail a test, so if you have
assert(true);
it will always pass.
assert(false);
it will allways fail.
use the conditions you need to test within assert. i.e.
assert(employeeType.equals("Junior Developer"));

Comparing a Scanner to a String

I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.

I'm having trouble only inputting letters, not numbers

For my project I need to input a first and last name with no numbers but I simply can't find anything online. If you could help, that would be terrific.
Also if you have the time, I need to flip the first and last name with a comma when the user inputs them.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class PhoneListr {
public static void main (String[] args) throws IOException {
String firstName;
String lastName;
System.out.println ("Please enter your first name:");
firstName = PhoneList ("");
System.out.println ("Please enter your last name:");
lastName = PhoneList ("");
System.out.println ("Your full name is: " + lastName + "," + firstName);
}
public static String PhoneList (String input) throws IOException {
boolean continueInput = false;
while (continueInput == false) {
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (System.in));
input = bufferedReader.readLine();
continueInput = true;
if(input.matches("[a-zA-Z]+")) {
continueInput = true;
}
else {
System.out.println ("Error, you may only use the alphabet");
continueInput = false;
}
}
return input;
}
}
use String.matches(regex):
if(input.matches("[a-zA-Z]+")) {
System.out.println("your input contains no numerics");
}
else {
System.out.println("only alphabets allowed");
}
the above regex checks a through z, or A through Z, inclusive (range).
For this type of string matching you need to use Regular Expressions, or "RegEx"es. It is a very big topic to cover but here's an introduction. RegExes are tools used to test whether strings match certain criteria, and/or to pull certain patterns out of that string or replace certain parts that match those patterns with something else.
Here is an example using a RegEx to test whether your input contains a digit:
if(input.matches("\\d")) {
// matched a digit, do something
}
Based on OP problem and clarification here are few suggestions.
Chaitanya solution handles the check for only alphabets perfectly.
About the neglected areas of problem :
i would advice you to make two variable firstName and lastName inside the main()
String firstName;
String lastName;
Change retun type of method phoneList() to String
return the entered name input insted of number inside the method phoneList ( dont actually see why you are returning number) and store it inside the firstName and lastName
System.out.println ("Please enter your first name:");
firstName = PhoneList (0);
System.out.println ("Please input your last name:");
lastNamr =PhoneList (0);
now to print it in the "comma format" use
System.out.println("full name is: " +lastName+ "," +firstName);
As i read your program again , its a mess!!
About the method phoneList()
Use regex condition to set continueInput to true/flase and not exploit execptions.
P.s. I would appreciate "editing" to post , if any fellow member find any mistakes above, using a mobile, not sure about formatting etc. Thanks. :-) (y)
You can also use
if(input.matches("[^0-9]"))
{
System.out.println("Don't input numbers!");
continueInput = false;}
Can't understand what 2nd question asks. For answer what I get from your 2nd question is like this.
In main function change the code like this
String first_name = null;
String last_name = null;
System.out.println ("Please enter your first name:");
first_name = PhoneList();
System.out.println ("Please input your last name:");
second_name = PhoneList();
System.out.println (second_name+","+first_name);
then in PhoneList function last line should be changed to
return input;
Please check for a link! for more info
You can add a check by passing the argument to method StringUtils.isNumeric
This returns true if the String entered is numeric

Restrict string input from user to alphabetic and numerical values [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.
my current code:
switch (studentMenu) {
case 1: // Change all four fields
System.out.println("Please enter in a first name: ");
String firstNameIntermediate = scan.next();
firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
System.out.println("Please enter in a middle name");
middleName = scan.next();
System.out.println("Please enter in a last name");
lastName = scan.next();
System.out.println("Please enter in an eight digit student ID number");
changeID();
break;
case 2: // Change first name
System.out.println("Please enter in a first name: ");
firstName = scan.next();
break;
case 3: // Change middle name
System.out.println("Please enter in a middle name");
middleName = scan.next();
break;
case 4: // Change last name
System.out.println("Please enter in a last name");
lastName = scan.next();
case 5: // Change student ID:
changeID();
break;
case 6: // Exit to main menu
menuExit = true;
default:
System.out.println("Please enter a number from 1 to 6");
break;
}
}
}
public void changeID() {
studentID = scan.next();
}
I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.
java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX methods.
Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
String word = sc.next();
System.out.println("Thank you! Got " + word);
Here's an example session:
Please enter letters:
&###$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
To validate that the next token is a number that you can convert to int, use hasNextInt() and then nextInt().
Related questions
Validating input using java.util.Scanner - has many examples!
It's probably easiest to do this with a regular expression. Here's some sample code:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
System.out.println(isNumeric("123"));
System.out.println(isNumeric("abc"));
System.out.println(isNumeric("abc123"));
System.out.println(isAlpha("123"));
System.out.println(isAlpha("abc"));
System.out.println(isAlpha("abc123"));
}
private static final Pattern NUMBERS = Pattern.compile("\\d+");
private static final Pattern LETTERS = Pattern.compile("\\p{Alpha}+");
public static final boolean isNumeric(String text)
{
return NUMBERS.matcher(text).matches();
}
public static final boolean isAlpha(String text)
{
return LETTERS.matcher(text).matches();
}
}
You should probably write methods of "getAlphaInput" and "getNumericInput" which perform the appropriate loop of prompt/fetch/check until the input is correct. Or possibly just getInput(Pattern) to avoid writing similar code for different patterns.
You should also work out requirements around what counts as a "letter" - the above only does a-z and A-Z... if you need to cope with accents etc as well, you should look more closely at the Pattern docs and adapt appropriately.
Note that you can use a regex to validate things like the length of the string as well. They're very flexible.
Im not sure this is the best way to do, but you could use Character.isDigit() and Character.IsLiteral() mabybe like this:
for( char c : myString.toCharArray() ) {
if( !Character.isLiteral(c) ) {
//
}
}
try regexp: \d+ -- numerical, [A-Za-z]+ -- alphabetical
I don't think you can prevent the users from entering invalid values, but you have the option of validating the data you receive. I'm a fan of regular expressions. Real quick, something like this maybe (all values initialized to empty Strings):
while (!firstName.matches("^[a-zA-Z]+$")) {
System.out.println("Please enter in a first name");
firstName = scan.next();
}
...
while (!studentID.matches("^\\d{8}$")) {
System.out.println("Please enter in an eight digit student ID number");
changeID();
}
If you go this route, you might as well categorize the different cases you need to validate and create a few helper methods to deal with each.
"Regex" tends to seem overwhelming in the beginning, but learning it has great value and there's no shortage of tutorials for it.
That is the code
public class InputLetters {
String InputWords;
Scanner reader;
boolean [] TF;
boolean FT;
public InputLetters() {
FT=false;
while(!FT){
System.out.println("Enter that you want to: ");
reader = new Scanner(System.in);
InputWords = reader.nextLine();
Control(InputWords);
}
}
public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
for(int i =0;i<b.length;i++){
if(b[i].matches("^[a-zA-Z]+$")){
TF[i]=true;
}else
{
TF[i]=false;
}
}
for(int j=0;j<TF.length;j++){
if(!TF[j]){
FT=false;
System.out.println("Enter only English Characters!");
break;
}else{
FT=true;
}
}
}

Categories