Java Name Program - java

Write a method called hasComma that takes a name as an argument and that returns a boolean indicating whether it contains a comma. If it does, you can assume that it is in last name first format. You can use the indexOf String method to help you.
Write a method called convertName that takes a name as an argument. It should check whether it contains a comma by calling your hasComma method. If it does, it should just return the string. If not, then it should assume that the name is in first name first format, and it should return a new string that contains the name converted to last name comma first format. Uses charAt, length, substring, and indexOf methods.
In your main program, loop, asking the user for a name string. If the string is not blank, call convertName and print the results. The loop terminates when the string is blank.
However, my program doesn't return the converted name. If I type in a name like John Smith, the program just ends, rather than returning Smith, John.
public static void main(String[] args) {
String name;
Scanner reader = new Scanner (System.in);
System.out.println("Type a name, then press ENTER.");
name = reader.nextLine();
if (name == null) {
return;
} else {
convertName(name);
}
}
public static boolean hasComma(String name) {
return name.indexOf(',') >= 0;
}
public static String convertName(String name) {
if (hasComma(name)) {
return name;
} else {
int index = name.indexOf(' ');
String first = name.substring(0, index);
String last = name.substring(index + 1);
String convertedName = last + ", " + first;
return convertedName;
}
}

You are not printing the output of your method.
Instead of
convertName(name);
write
System.out.println(convertName(name));

Related

How do you test that a string is the empty string

How do you test that a string str is the empty string?
Below is the code I tried, but when I just hit enter on eclipse console, it does not print right output which should be "String is Null"
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
out.print("Press Y to continue: ");
String yes= in.next();
int LengthOfInput = yes.length();
if (LengthOfInput==0)
{
out.print("String is Null");
}
else {
out.print("String not null");
}
}
}
Your method correctly identifies whether a string is empty. Other than this method, you can also call isEmpty on a string or check of the string is equal to ""
if (string.isEmpty())
if (string.equals(""))
The reason why your code did not work as expected is because you read the user input wrongly. next method by default will not return an empty string because it will always try to find something to read.
To achieve your intended behaviour call nextLine instead of next.

Variable Not Being Initialized in Function

I'm trying to create a program that prompts user to input a word and it would return the length of the words. However I'm having issues with "String word;", as I keep getting the error that local variable may not have been initialized.
import javax.swing.JOptionPane;
public class FunctionsTest {
public static void main(String[] args) {
String word;
JOptionPane.showMessageDialog(null, "The length of the word is" + findLength (word));
}//End of Main Method
public static int findLength(String word) {
String str = new String(word);
return str.length();
}//End of findLength Method
}
the "word" has no value,it's null, you need give "word" some value:
String word = "abc";
There is no user input being prompted, therefore the String word will never have a value. Create a user input prompt, and have the string equal to the value of the input.

Formal Greeting app only displays last if statement can't figure out why

package chapter6;
import java.util.Scanner;
public class formal_greeting {
public static void main(String[] args) {
String title;
String name;
String mr = null;
String miss = null;
String ms = null;
String mrs = null;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
name = input.next();
System.out.print("Enter your title: ");
title = input.next();
if (title.equalsIgnoreCase(mr)) {
System.out.println("Hello sir");
}else if (title.equalsIgnoreCase(miss)) {
System.out.println("Hello ma'am");
}else if (title.equalsIgnoreCase(ms)) {
System.out.println("Hello ma'am");
}else if (title.equalsIgnoreCase(mrs)) {
System.out.println("Hello ma'am");
}else {
System.out.println("Hello " + name);
}
}
}
I can't figure out why my if statements won't work. so far it only displays (Hello "name") can someone please tell me what is wrong with my if statement???
Problem is not in the if statements.Change your method input.next() to input.nextLine() .Because using next() you will get only what you entered before the space. But if you use nextLine() the Scanner will read the entire input line.For more reference click here.
Hope this helps
You need to know the difference between a String variable and a string literal.
In your code, mr is a string variable. The value that it stores is null as you can see from this line:
String mr = null;
In the if statement, you test whether the user input is equal to the value string variable. Let's say you entered "Mr" in the console:
User input Value of the mr variable
"Mr" null
Are they the same? No.
The same goes for all the if statements. Finally the execution comes to the else and executes the stuff there since every if statement failed.
What you need to do is to use a string literal instead of a string variable.
A string literal is denoted by double quotes:
"This is a string literal"
So your if statements would look like:
if (title.equalsIgnoreCase("mr")) {
/* ⬆︎ ⬆︎
Quotes here!
*/
Alternatively, you can use variables as well. But you should not give them a value of null. Instead, give them a string literal:
String mr = "mr";
// etc.
This way, you don't need to change your if statement.

Java program delays whitespace strings from printing to console

This is a problem I've encountered several times, and always wondered why.
For my code below as an example, if a string of whitespace is entered, the method will not print. However, after the next input with a value string containing characters, it will print all the whitespace strings and the valid character containing string. Why is this delayed and stored in memory?
Example for the code below:
Enter " " returns nothing.
Enter " " returns nothing.
Enter "SwiggitySwooty" returns " " \n " " \n "SwiggitySwooty"
Explaination: The whitespace containing strings are delayed until a valid character string is entered.
Extra info: I use intellij, also happens when not sending the string to a method. I've also had this happen during a while(input.hasNext()) statement, in which I try to catch an invalid input as a string, when I want to take an integer. If I enter 'n' amount of legitimate integers, and then a string, it would print out my "please enter an integer" that 'n' amount of times like in this code.
Lastly, if anyone thinks of a better title for this, let me know so I can change it for more exposure for those with similar questions. Thank you.
Let me know if you guys need anything else!
/**
* Created by JacobHein on 4/19/15.
*/
import java.util.Scanner;
public class FizzString {
/*TODO
* Given a string str, if the string starts with "f" return "Fizz".
If the string ends
* with "b" return "Buzz". If both the "f" and "b" conditions are true, return
* "FizzBuzz". In all other cases, return the string unchanged. */
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
while(input.hasNext()) {
System.out.println(fizzString(input.nextLine()));
}
}
public static String fizzString(String str) {
String result=str;
int l=str.length();
if (str.charAt(0)=='f'||str.charAt(l-1)=='b') {
result="";
if (l>0) {
if (str.charAt(0)=='f') {
result="Fizz";
}
if (str.charAt(0)=='b') {
result="Buzz";
}
if (l>1) {
/*technique: continue the process if l>1 (within l>0 if statement),
prevents breaking the program.*/
if (str.charAt(l-1)=='b') {
result="Buzz";
}
if (str.charAt(0)=='f'&&str.charAt(l-1)=='b') {
result="FizzBuzz";
}
}/*end l>1*/
}/*end l>0*/
}/*end charAt if*/
return result;
}
}
I believe this is what you're looking for:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputLine = "";
do {
inputLine = input.nextLine();
System.out.println(fizzString(inputLine));
System.out.println("");
} while (inputLine.length() > 0);
System.out.println("Goodbye");
}
public static String fizzString(String str) {
// Given a string
// If both the "f" and "b" conditions are true, return FizzBuzz
if (str.startsWith("f") && str.endsWith("b")) {
return "FizzBuzz";
}
// If the string starts with "f" return "Fizz".
if (str.startsWith("f")) {
return "Fizz";
}
// If the string ends with "b" return "Buzz".
if (str.endsWith("b")) {
return "Buzz";
}
// In all other cases, return the string unchanged.
return str;
}
Results:
The problem is the behavior of the Scanner class:
The next and hasNext methods and their primitive-type companion methods
(such as nextInt and hasNextInt) first skip any input that matches the
delimiter pattern, and then attempt to return the next token. Both
hasNext and next methods may block waiting for further input. Whether a
hasNext method blocks has no connection to whether or not its
associated next method will block.
Internally, the Scanner class is performing the following operation:
while (!sourceClosed) {
if (hasTokenInBuffer())
return revertState(true);
readInput();
}
The method hasTokenInBuffer() skips all the delimiter tokens (by default is \p{javaWhitespace}+), so only when the class found a non-delimiter token, it returns true in the hasNext() method.
For example, if you type this content: "\n\n\n5\n" and then execute nextInt() method, you'll obtain a result of 5, because Scanner automatically skips all the return line characters.
If you want to find some string into a line, try with the method java.util.Scanner.findInLine instead of nextLine().
Use the patterns: ^f(.)* to look for every line that starts with a f character and the pattern (.)*b$ to look for every line that ends with a b character.

Checking string formats in Java?

having problems doing something for a class I'm taking, since I missed a class or two. (I know it's looked down on to 'do someone's homework,' but I'm not looking for that.)
The assignment is as follows:
Write a program to do the following:
Prompt for input of someone's first, middle, and last name as a single string (using any combination of upper and lowercase letters).
Check to make sure the name was entered in the correct format (3 names separated by spaces). If the input is not correct, continue to request the input again until the format is correct.
Capitalize only the first letters of each part of the name, and print out the revised name.
Print out the initials for that name.
Print out the name in the format of: Lastname, Firstname, MI.
The major problem I'm having is the second part of the assignment; I got the first part, and I'm fairly sure I can manage through the rest, after I get the second set up.
import java.util.*;
public class TestStrings
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
String name;
System.out.print("Enter your name as 'First Middle Last': ");
name = key.nextLine();
}
}
From what I've gathered, I need to use the string.split? I'm not sure how to go about this, though, since I need to check to make sure there are three spaces, that aren't just right next to each other or something, such as "John(three spaces)Doe". I assume it's going to be some kind of loop to check through the input for the name.
The catch 22, is that I can't use arrays, or StringTokenizer. I must use the substring method.
Any help would be appreciated. Thanks. :D
To point you in the right direction to find the first name(since you cant use arrays):
String firstName = input.substring(0, input.indexOf(" "));
This will get you a substring from the start to the first space. If you research the indexOf and substring methods you should be able to go from there.
Look at the matches method if you know how to use regex. If not think about indexOf and substring methods.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
You can use the substring and the indexOf functions of String class to get what you need.
String#indexOf: Get's the position of a String inside a String.
String#substring: Get's a substring contained in a String.
String s = "Luiggi Mendoza J.";
String x;
while(s.indexOf(" ") > 0) {
x = s.substring(0, s.indexOf(" "));
System.out.println(x);
s = s.substring(s.indexOf(" ") + 1);
}
x = s;
System.out.println(x);
The program output will be:
Luiggi
Mendoza
J.
Use a while loop to continuously check whether user entered a string that consists of 3 parts which are seperated via a single space character ' ', then use split() function to verify 3 parts of string. By using substring() as demonstrated here you can get names seperately:
public static void main ( String [] args )
{
String name = "";
boolean ok = false;
Scanner key = new Scanner( System.in );
while ( !ok )
{
System.out.print( "Enter your name as 'First Middle Last': " );
name = key.nextLine();
try
{
if ( name.split( " " ).length == 3 )
ok = true;
}
catch ( Exception e ){ }
}
if ( ok )
{
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstName.length()+1,
name.lastIndexOf(" "));
String surname = name.substring(middleName.length()+firstName.length()+2,
name.length());
}
}
This works using Pattern/Matcher and regexs. Also guards against strings of length 1 when adjusting case.
private static String properCase(String str) {
return str.substring(0, 1).toUpperCase()
+ (str.length() >= 1 ? str.substring(1).toLowerCase() : "");
}
public static void main(String[] args) {
boolean found = false;
do {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name as 'First Middle Last': ");
Pattern p = Pattern.compile("\\s*(\\w+?)\\s(\\w+?)\\s(\\w+)+\\s*");
Matcher m = p.matcher(scanner.nextLine());
found = m.find();
if (found) {
String first = m.group(1);
String middle = m.group(2);
String last = m.group(3);
String revised = properCase(first) + " " + properCase(middle)
+ " " + properCase(last);
System.out.println(revised);
System.out
.printf("%s %s %s.\n", properCase(last),
properCase(first), middle.substring(0, 1)
.toUpperCase());
}
} while (!found);
}

Categories

Resources