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"));
Related
I am new at programming. I want to make a program that checks the input name and password are same or not, if it is, the program must say "Your name and your password cannot be same".My code is like below but even both of two input are same or different, result is same. What am i doing wrong?
import java.util.Scanner;
public class project {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter Your Name ");
String name =scan.nextLine();
System.out.println("Please Enter Yout Password for register");
String password=scan.nextLine();
if(name.equals(password.startsWith(password))) {
System.out.println("Your name and your password cannot be same");}
else {
System.out.println("Register is successful");
}
}
}
You should change this line:
if(name.equals(password.startsWith(password))) {
To:
if (name.equals(password)) {
Why it fails
It seems that you inadvertently added .startsWith(password) into the condition.
Explanation about what's happening
The expression password.startsWith(password) returns the boolean value true. Which causes the condition for the if statement to be: if(name.equals(true)) which always returns false because a String never equals() a boolean.
Essentially the idea of this program is to test user input and throw exceptions that I've created when invalid data is entered. For example: name cannot be empty and must be all alpha characters (no special or numeric). I have embedded this in a do-while loop that will continue so long as q is not entered to quit. I'm reading in the user input via scanner line and then sending the string inputted to a function that validates whether it meets the criteria. If it does not, then the function throws my custom exceptions. It all works fine EXCEPT when the exception is thrown it still takes that string and puts it in the new Person object.
How do I throw the exception to the user but THEN require them to re-enter the name or age until it's entered correctly?
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter person info or q to quit.");
System.out.print("Please enter the name of this person:");
String name = input.nextLine();
if(name.equalsIgnoreCase("q"))
{
break;
}
try{
isName(name);
}catch (InvalidNameException n){
System.out.println(n);
}
System.out.print("Please enter an age for this person:");
String age = input.nextLine();
try{
isValidAge(age);
}catch(InvalidAgeException a){
System.out.println(a);
}
public static void isName(String name) throws InvalidNameException
{
if(name.isEmpty())
{
throw new InvalidNameException("You did not enter a name.");
}
String[] namez = name.split(" ");
for(int i=0;i<namez.length;i++)
{
char[] charz = namez[i].toCharArray();
for (char n : charz)
{
if(!Character.isLetter(n))
{
throw new InvalidNameException("You have entered an invalid name.");
}
}
}
}
Put a continue; in your exception handling. It will break the loop an reenters it.
I would assume that the error lies within the compatibility of your isName() method and the method loop shown. It probably happens after it sets the name to a variable too. I cant tell you anything really specific because I cant see the isName method though.
The easiest way I know of doing this is to validate the obtained String using a regular expression. You can do something like this:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
String regex = "[A-Z a-z]+(\\s)[A-Z a-z]+";
System.out.println(name.matches(regex)? "matches": "does not match");
The expression regex is used to evaluate a sequence of alpha characters (no numbers or special characters) separated by a space. So, something like: "Joe Smith" will pass validation, but something like "Joe 123Klkjsd" will not.
You can take this code and test the input String in a while() loop:
while(!name.matches(regex))
{
// Prompt the user to re-enter a valid name and assign to name variable
}
Something like that should work.
It would be better to evaluate each variable within a do-while loop. Thus if there is an error in the variable age would not necessarily re-enter the name.
Scanner input = new Scanner(System.in);
String name;
String age;
System.out.println("Enter person info or q to quit.");
do{
System.out.print("Please enter the name of this person: ");
name = input.nextLine();
if(name.equalsIgnoreCase("q")) break;
try{
isName(name);
break;
}catch (InvalidNameException n){
System.out.println(n);
continue;
}
} while (true);
if(!name.equalsIgnoreCase("q"))
do{
System.out.print("Please enter an age for this person: ");
age = input.nextLine();
if(age.equalsIgnoreCase("q")) break;
try{
isValidAge(age);
System.out.printf("Nombre; %s\nEdad: %s",name,age);
break;
}catch (InvalidAgeException a){
System.out.println(a);
continue;
}
} while (true);
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.");
}
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
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;
}
}
}