I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
String name;
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry "))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
Check out this related question:
Test if a string contains any of the strings from an array
Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.
Use the OR symbol "||" or "|".
Such as if (name.equals("barry ") || name.equals("sara"))
For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.
basically, you need an "Or" gate, this would work:
if(name.equals("name1")||name.equals("name2")||name.equals("name3"))
etc...
Related
import java.util.Scanner;
public class ValidateMe {
public static void main(String[] args) {
int c;
String d;
Scanner scnr = new Scanner(System.in);
c = getValidIntScore(scnr);
d = getValidStrName(scnr);
}
public static int getValidIntScore(Scanner scnr){
int c;
System.out.println("Enter an integer test score between 0-100 inclusive:");
c = scnr.nextInt();
while (c < 0 || c > 100) {
System.out.println("Test score must be a value between 0-100 inclusive. Enter the test score:");
c = scnr.nextInt();
}
return c;
}
public static String getValidStrName(Scanner scnr){
String c;
System.out.println("Enter student's full name:");
c = scnr.nextLine();
while (c.isEmpty()){
System.out.println("Name must be non-empty and non-blank. Enter the student's full name:");
}
return c;
}
}
When I run this, I can get the test score just fine, but when I get to the student's name, I cannot even enter input and it keeps running over and over... How can I fix this?
You have 2 problems in this;
mixing nextX and nextLine without setting delimiter
You can't mix nextLine and next(anything else) without things going rather wrong. It sounds like you want one enter to be equal to one input. That's easily done:
Update the scanner to tell it that you want it to scan for newlines, not whitespace. After making the scanner (new Scanner), immediately run:
scanner.useDelimiter("\r?\n");
Which tells it that input is separated by newlines (enter presses). All other solutions (such as throwing nextLine() calls in to 'reset' it) result in issues if the user enters space-separated things when you ask for non-full-line inputs (even though it is extremely common advice here on SO, the delimiter thing is simpler and doesn't fail in such cases).
Not re-reading in the loop
Computer does as it is told.
You are asking it: Hey, as long as c is empty, do the following: print that c is not empty.
So, it'll just spam that line over and over. c is empty and will remain empty forever, which is why it does that. You'd have to update c inside that while block at the end there, e.g. with c = scanner.nextLine();.
I currently have an assignment on creating a user interface with while loop, here is my code so far:
import java.util.Scanner;
public class Part3{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Welcome dear user!");
System.out.println("Would you like to:");
System.out.println("a) sum gain");
System.out.println("b) exit");
System.out.print("Option: ");
String optionString = input.next();
char option = optionString.charAt(0);
while (option == ("a")){
System.out.println("Helo");
}
}
}
I'm stuck with the while loop, when I compile, it is error say a bad operand types for binary operator. I'm new to java so can you guys help me out with this. Thanks a lot
You might be facing the following issue:
Part3.java:14: error: incomparable types: char and String
while (option == ("a")){
Because you're trying to compare a char (option) and a String ("a"). So do use 'a' instead of "a".
Even when you'll resolve this issue, it seems that your code will stuck into a infinite loop when user will choose option a.
If you wanna print it only one time use break; statement inside loop.
while (option == ("a")){
System.out.println("Helo");
break;
}
I'm trying to prevent the user from inputting spaces or no values.
but nothing works. Even with no entered values program goes further without printing my error. What am I doing wrong?
my code example
Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");
String newcomer = nameScan.nextLine();
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();
if (userName.length()==0) {
System.out.println(" ");
System.out.println("You have to set up a player name first... ");
System.out.println(" ");
}
else {...
As #11thdimension said, you have to validate the input.
You can do something like:
if (newcomer.isEmpty()) {
System.out.println("Please write something");
}
Or you can do a while loop and keep asking for a correct input.
Your code
if(username.length() == 0)
will not check whether the username contains space because space is counted towards the length of the String.
To check for empty String input(which may contain space(s)), you can do:
if("".equals(username.replaceAll("\\s+",""))) //or
if("".equals(username.trim()) //or
if(username.isEmpty())
Further more, you would want to use a do-while loop for validation instead of using an if-statement.
I'm writing a program that asks the user to enter their last name in lower case and asks them if they want it outputted as all caps or with just the first letter capitalised. The problem I'm having is using charAt with toUpperCase.
import java.util.Scanner;
//This imports the scanner class
public class ChangeCase {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
//This allows me to use the term scan to indicate when to scan
String lastName;
//sets the variable lastName to a string
int Option;
System.out.println("Please enter your last name");
//Prints out a line
lastName = scan.nextLine();
//scans the next line of input and assigns it to the lastName variable
System.out.println("Please select an option:"+'\n'+"1. Make all leters Capitalised"+'\n'+ "2. Make the First letter Capitalised");
Option = scan.nextInt();
if (Option == 1){
System.out.println(lastName.toUpperCase());
}
if (Option == 2){
System.out.println(lastName.charAt(0).toUpperCase());
}
}
}
I get an error saying "Cannot invoke toUpperCase() on the primitive type char"
You can't apply String.toUpperChase on a char like your error is saying. In the case where you want to make the first letter uppercase you can do something like:
String lastName = "hill";
String newLastName = lastName.substring(0, 1).toUpperCase() + lastName.substring(1);
System.out.println(newLastName);
A sample run of this:
run:
Hill
BUILD SUCCESSFUL (total time: 0 seconds)
In the case where you want all the letters uppercase, it's as simple as
newLastName = lastName.toUpperCase();
System.out.println(newLastName);
A sample run of this:
run:
HILL
BUILD SUCCESSFUL (total time: 0 seconds)
I used to try this in C programming in college. Should work here as well.
(char)(lastName.charAt(i) - 32)
Try the above in System.out.println
The code when we deduct 32 from character it reduces ascii value by 32 and hence gets upper case letter. Just refer an ascii table to understand what I am trying to tell by deduction of 32 places in the table.
As your error is telling you, you can't invoke String.toUpperCase() on a primitive char type.
System.out.println(lastName.charAt(0).toUpperCase());
But, you can invoke Character.toUpperCase(char) like
System.out.println(Character.toUpperCase(lastName.charAt(0)));
Or, call String.toUpperCase() and then take the first character. Like,
System.out.println(lastName.toUpperCase().charAt(0));
After reading the string methods description in a chapter i was trying to solve this programming exercise. here it is.
Write a program that asks for the user's name and then writes that name to the monitor with either "Ms." or "Mr." in front, depending if the name is for a female or male. Assume that the only female names are
Amy
Buffy
Cathy
and that the only male names are
Elroy
Fred
Graham
All other names will be echoed without a title. The program continues looping until the user hits "enter" without first typing a name.
C:\>java Title
Enter a name:
Amy Johnson
Ms. Amy Johnson
Enter a name:
Fred Smith
Mr. Fred Smith
Enter a name:
Zoltan Jones
Zoltan Jones
Enter a name:
C:\>
here is my code i know its wrong because i am very confused.
import java.util.Scanner;
class titleApplier {
public static void main(String[] args) {
String name;
String male = {"Elroy" , "Fred " , " Graham"};
String females = {"Amy", "Buffy", "Cathy"};
Scanner scan = new Scanner(System.in);
while(name.hasNext()) {
System.out.println("Enter a name ");
name = scan.nextLine();
if(name.equals(male)) {
System.out.println("Mr " + male);
}
else if (name.equals(females)) {
System.out.println(" Mrs " + females);
}
else {
System.out.println(scan.nextLine());
}
}
}
}
You're mostly on the right track, good work!
Instead of storing the names in Strings individually, you could just reference them directly in your if statements as such:
if(name.equals("Elroy") || name.equals("Fred") || name.equals("Graham")) {
System.out.println("Mr " + male);
}
Also, since you're providing first and last names, I don't think you should be matching with the equals method, but instead, checking to see if the name contains one of the names:
if (name.contains("firstName"))
As this looks like homework, try something along the same lines for the women yourself. Let me know if you have anymore questions. Good luck!
There are plenty of errors in your program which need to be corrected.Better give this a try.I have used BufferedReader since the Scanner class causes some problems while taking several input values within a loop.:-
import java.io.*;
import java.util.*;
class MF{
static boolean search(String arr[],String st){
for(int i=0;i<arr.length;i++){
if(arr[i].equalsIgnoreCase(st)==true)
return true;
}
return false;
}
public static void main(String args[])throws IOException{
String male[]={"Elroy","Fred","Graham"};
String fem[]={"Amy","Buffy","Cathy"};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:-");
String st=br.readLine();
if(st.equals("")==false){
StringTokenizer str=new StringTokenizer(st);
String tok=str.nextToken();
if(search(male,tok)==true)
System.out.println("Mr."+st);
if(search(fem,tok)==true)
System.out.println("Ms."+st);
}
else
break;
}
System.out.println("Program terminates.");
}
}
A few observations from your code:
male and females should be arrays of String, not just a single String. (i.e. String[] females = {"Amy", "Buffy", "Cathy"};
Watch out for leading and trailing white spaces. "Fred" and "Graham" will never pass a comparison unless you call the String.trim() method.
The method hasNext() is not defined in the String class; thus the compilation error. If you are writing this on an IDE such as Eclipse, read the errors you are getting and resolve them. Even for a beginner this should not be difficult at all.
Your program prompts the user AFTER the name is already entered. This might be easier if you enclose your code in a do/while rather than in a while loop. This is a matter of preference, or course. Also, normally you would want the user input to appear in the same line as the prompt, so use System.out.print() for the prompt instead of System.out.println().
When you are learning, you should always try your programs with very controlled inputs. In this case, you should have tried the program with a single male name and female name, and once you got that part working, then you should try expanding your solution to handle multiple names.
Your code allows to enter a LINE (words separated by space) rather than a String (array of characters with no white spaces). Therefore, you need to break that line into tokens (words) and examine either the first token (first name) or the second token (last name) and compare it to the names in the array. Otherwise, the equals() method will return false. This is because 'Elroy Smith' is not equal to 'Elroy'. You can do what I just explained, or use other String methods such as contains() or startsWith().
You should append the title to the entered name, and not the first name in your String array. Instead of outputting "Mrs. Amy", your program should output "Mrs. Amy Smith".
Your while() clause does not capture this requirement: "The program continutes looping until the user hits "enter" without first typing a name." This method will always return true even if the line has a length of zero. Instead, use the String entered and loop only if the length of the String entered is larger than zero.
To eliminate unnecessary processing, you can use a boolean variable to see if the name has been found, in order to break (exit loop) or continue (skip to next iteration).
This is one potential solution (might not be the most effective, but easy for you to follow):
public static void main(String[] args)
{
String name;
String[] males = {"Elroy", "Fred ", " Graham"};
String[] females = {"Amy", "Buffy", "Cathy"};
Scanner scan = null;
do
{
System.out.print("Enter a name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
boolean found = false;
// Search all possible male names
for (String temp: males)
{
if (name.startsWith(temp))
{
System.out.println("Mr. " + name + "\n");
found = true;
break; // stop looping if found
}
}
if (found) { continue; } // skip the rest of the loop if name has been found
// Search all possible female names (only if name has not been found)
for (String temp: females)
{
if (name.startsWith(temp))
{
System.out.println("Ms. " + name + "\n");
found = true;
break;
}
}
if (name.length() > 0 && !found)
{
// A name was entered but it was never found
System.out.println("Unknown name entered.\n");
}
} while (name.length() > 0);
scan.close();
}
The output:
Enter a name: Fred Smith
Mr. Fred Smith
Enter a name: Buffy Vampire Slayer
Ms. Buffy Vampire Slayer
Enter a name: Cathy Doe
Ms. Cathy Doe
Enter a name:
Exiting program.