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.
Related
I am working on a Lab on the site Zybooks and I have completed the following code below:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName;
String middleName;
String lastName;
firstName = scnr.next();
middleName = scnr.next();
lastName = scnr.nextLine();
if (lastName.contains("")){
System.out.println(middleName + ", " + firstName.charAt(0) + ".");
}
else {
lastName = lastName.substring(1);
System.out.println(lastName + ", " + firstName.charAt(0) + "." + middleName.charAt(0) + ".");
}
}
}
The Exception Error that I receive is this:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at LabProgram.main(LabProgram.java:13)
When I run the following code in an IDE everything works just fine. However when I try running it in Zybooks I get an exception error. I've come to learn that this is because when I don't add a space after I enter two names that Zybooks gives an exception error. However when I add a space after the last name the code compiles as intended. For grading purposes I need the code to compile without a space from the keyboard, thus I am asking how I can get this code to compile. I've tried manually adding whitespace but nothing has worked.
Any help would be very much appreciated
Looking at the code it's obvious that you have three (3) specific User entry prompts to deal with. The User must supply a First Name, then the User needs to supply a Middle Name, and then finally the User needs to supply a Last Name. As with any input each of these names needs to be validated for proper context. This would include the rules for names, for example everyone has a First Name and Last Name but not everyone has a Middle Name also first and last names can contain two name words (ex: De Vanderholt).
When you have three specific prompts for the User to fill in then let them know exactly where they are at. Display on Screen what the User is expected to enter. It's always a good idea to place each prompt into a loop so that the input can be validated and if there is a problem the User is given the opportunity to provide actual valid data (in this case a valid name).
In your code you use the Scanner#next() method to retrieve the input for both First Name and Middle Name(s) however this method will not play well with multi word names since the next() method is token based. This means that if a two word name is supplied to the First Name prompt then only the first word is retrieved and the second word is automatically applied to the Middle Name prompt. You don't even get a chance to enter the middle name. This is no good unless special code is put in place to take car of this situation. It's just better not to use the next() method in this case and simply use the Scanner#nextLine() method for all your prompts. Keep in mind however that the Scanner#next() method will work just fine if you know that only a single name word will be provided by the User but this method is better used in conjunction with the Scanner#hasNext() method.
Look at your code. As said earlier, everyone has a Last Name but not everyone has a Middle Name so why have this line of code (unless your rules include the fact that last names can be nothing):
if (lastName.contains("")){
It should actually never be allowed to come to this scenario where the last name contains nothing, don't even accept the fact unless it's a middle name. If the supplied Last Name was validated then you would never need to worry about this situation unless of course your rules allow it. The example code below does not allow it.
Because there are three prompt which basically do the same thing and require the same basic validation a helper method (getName()) is used so as to eliminate the need for duplicate code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// First Name:
String firstName = getName(scnr, "First");
// Middle Name:
String middleName = getName(scnr, "Middle");
// Last Name:
String lastName = getName(scnr, "Last");
System.out.println(new StringBuilder("")
.append(lastName).append(", ")
.append(firstName.charAt(0))
.append(". ")
.append(middleName.isEmpty() ? "" : middleName.charAt(0))
.append(middleName.isEmpty() ? "" : ".").toString());
// O R
/*
System.out.println(new StringBuilder("")
.append(lastName).append(", ")
.append(firstName)
.append(" ")
.append(middleName)
.toString());
*/
// O R
/*
System.out.println(new StringBuilder("")
.append(firstName)
.append(" ")
.append(middleName)
.append(middleName.isEmpty() ? "" : " ")
.append(lastName)
.toString());
*/
}
The Helper Method (getName()):
private static String getName(final Scanner scnr, final String nameTitle) {
String name = "";
while (name.isEmpty()) {
System.out.print("Enter your " + nameTitle + " Name: --> ");
// Get input and trim off leading/trailing whitespaces, etc
name = scnr.nextLine().trim();
// Is this for a Middle Name?
if (nameTitle.equalsIgnoreCase("middle")) {
// If nothing was supplied then there is no
// middle name so break out of prompt loop.
if (name.isEmpty()) {
break;
}
}
// Validate name...
/* Does the supplied name only contain A to Z characters
in any letter case. Add characters to the regular
expression as you see fit. (?i) means any letter case. */
if (name.matches("(?i)[A-Z. ]+")) {
// Yes, it does...
/* Ensure 'first' character of each name word (if more than one)
is upper letter case. */
String[] tmp = name.split("\\s+");
StringBuilder nme = new StringBuilder("");
for (String str : tmp) {
if (!Character.isUpperCase(str.charAt(0))) {
str = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
if (!nme.toString().isEmpty()) {
nme.append(" ");
}
nme.append(str);
}
name = nme.toString();
}
// No it doesn't so inform User of the mistake and to try again.
else {
System.err.println("Invalid " + nameTitle + " Name Supplied! (" + name + ") Try Again...");
name = ""; // Set to null string so as to re-prompt.
}
}
return name;
}
This question already has answers here:
Prompt user to enter name on one line and print it out as "Last, First"
(4 answers)
Closed 6 years ago.
So far I have the following code:
import java.util.*;
public class Names {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.next();
changeNameFormat(name);
}
public static void changeNameFormat(String name) {
System.out.println(name.substring(0,20));
}
}
I am not sure, but I think I need to use an array, however I am unsure of how to go about this seeing as I will not know what the user input will be every time.
Example of what I want to happen:
User inputs:
John Smith
I want the program to output it as this:
Smith, John
Lets suppose you ask the user to enter the first name and last name with a comma separation.
For example: FirstName,LastName
In this case you can use comma as the delimiter for identifying first name and last name.
public static void changeNameFormat(String name) {
String [] splitName = name.split(",");
//splitName[0] holds first name and splitName[1] holds last name
System.out.println(splitName[1] + ", " + splitName[2]);
}
An easier way without manipulating / splitting one String is to use the Scanner's default delimiter (whitespace):
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
// assuming the input consists in name surname[return]
String name = input.next();
String surname = input.nextLine();
System.out.printf("%s, %s%n", surname.trim(), name.trim());
input.close();
You can do the following in the changeNameFormat
System.out.println(name.replaceAll("^(\\w+)\\s+(\\w+)$", "$2, $1"));
Also, remember to change the input.next() to input.nextLine() to be able to read multiple words in one line. For more detail on the regex, please refer to the following link:
https://regex101.com/r/sA4xJ5/2
Sorry if there is a obvious answer and I'm not seeing it but I'm new to programming. I'm trying to use tokens from a .txt file as variables in a method but originally declared in another method. An example of line of code from txt file is:
Lisa 0 0 0 0 464 38 1 6 31 113 298
My code gathers data from the user and locates that name from text file and uses its data. The code that i need from the text file is the integers only.
public static void name(String n, Scanner NAME){
while(NAME.hasNextLine()){
String name2 = NAME.next();
if(name2.equalsIgnoreCase(n)){
System.out.println("Popularity ranking of name \"" +name2+ "\"");
int num1=0;
for(int i = 0; i<LS; i++){
System.out.println(((i*10)+YEAR)+ ": " + num1);
num1=NAME.nextInt(); //where the tokens i need are
//serving as attention getter
}
}
}
System.out.println("Name not found");
}
public static void intro(){
System.out.println("This program graphs the popularity of a name");
System.out.println("in Social Security baby name statistics");
System.out.println("recorded since the year 1900.");
Scanner console=new Scanner(System.in);
System.out.println("Type a name: ");
String n = console.next();
name(n,NAME);
graphData(NAME);
}
}
The place where I'm trying to use the tokens is the following:
public static void graphData(Scanner NAME){
while(NAME.hasNextLine()){
int num=NAME.nextInt();
for(int i = 0;i<LS;i++){
g.drawString("" + num,i*WIDTH,30+(num/2)); //part specifically
num.nextInt(); //where im trying to use the tokens
}
}
}
This is not the complete program, only what I feel is necessary. Note that there are four class constants (YEAR, NAME, LS, and WIDTH). They cannot be changed and I cannot use arrays in this program.
Any thoughts on how i can go about doing it?
I've been looking everywhere but can't find anything. I've also tried a couple of things such as rewriting were the tokens were in names() and applying it to graphData().
make graphData() graph only a single point and pass each int to graphData as its read in name()
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...
I'm making a program that reads a person's name and age, and when "zzz" is entered, it prints the names and ages of everyone who's 18 or older. Also, I want to calculate the percentage of people who's 18 or older. But, here's the problem: the code i'm posting bellow, only prints the first name (example: "Ricardo Almeida" and age "19". Output: "Ricardo : 19", but i want "Ricardo Almeida : 19). The percentage calculation has a error too but i cant figure out whats wrong. It gives 0 all the times. (DONE!) Thanks in advance to anyone who's reading this and trying to help.
PS: I dont want to use arrays! I already learned how to use them, but i want to know how to solve this without using them :)
package javaapplication38;
import java.util.Scanner;
public class JavaApplication38 {
private static final Scanner in=new Scanner(System.in);
private static String metodo1(String name, int age) {
String frase="";
if (age==18 | age>18) {
frase=String.format("%s : %d %n",name,age);
}
return frase;
}
public static void main(String[] args) {
int age, counter1=0, counter2=0;
String name, acumtxt="", aux;
do {
System.out.print("Name: ");
name=in.next(); in.nextLine();
if (!"ZZZ".equalsIgnoreCase(name)) {
counter1++;
do {
System.out.print("Age: ");
age=in.nextInt();
} while (age<=0);
if (age==18 | age>18) {
counter2++;
}
aux=metodo1(name,age);
acumtxt+=aux;
}
} while(!"ZZZ".equalsIgnoreCase(name));
System.out.print(acumtxt);
if (counter1>0) {
System.out.println("The percentage of people who's 18 or older is "+ (counter2/counter1) +"%.");
}
}
}
It seems that your problem is here
name=in.next(); in.nextLine();
In this code next() reads and returns only one word from line until it finds whitespace or end of line. Rest of it is consumed with readLine(), but you ignore its result. Try maybe to with
name=in.nextLine();
to read entire line.
After that you will also have to change
age=in.nextInt();
and either use
age=Integer.parseInt(in.nextLine());
or add in.nextLine() after it to also consume new line marks which would affect next name question.
age=in.nextInt(); in.nextLine();//add in.nextLine(); to consume new line marks
in.next() will read until there is a whitespace. You can use in.nextLine (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()) or use [BufferedReader](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html) instead, and you can call the readLine() method.