I just started learning Java and I'm having trouble formatting string. In the problem I have a string a user inputted that is a name in the format: "First Middle Last". I need to output the string in the format: "Last, First MI. " (MI is middle initial).
Here is what I have so far, I have the first name working, but unsure how to go about getting the last and middle initial out of the string.
// Variable declarations
String name, first, last, middle;
Scanner scan = new Scanner (System.in);
// Get name from user in format "First Middle Last"
System.out.println("Enter the person's name: ");
name = scan.nextLine();
// Get first, middle initial, and last name from the string
first = name.substring(0, name.indexOf(" "));
middle =
last =
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middle + ".");
so for example if the user entered: "John Robert Doe", it would output as "Doe, John R."
Any help is appreciated.
You can use the split method of the String class
// Get first, middle initial, and last name from the string
String nameParts [] = name.split(" ");
// not sure if you need these variables, but I guess you get the picture
first = nameParts [0];
middle = nameParts [1];
last = nameParts [2];
middleInital = middle.charAt(0);
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middleInital + ".");
Take a look at the String.split method. This allows you to find the substrings. Then you only have to place them in the correct order
Take a look at String split and charAt method of String class.
String person_data = "John Robert Doe" ;
String[] data = person_data.split(" ");
char MI = data[1].charAt(0);
System.out.println(data[2] +","+ data[0] + " "+ MI);
Output = Doe,John R
Here
Data[0] == "John"
Data[1] == "Robert"
Data[2] == "Doe"
MI = first character of Data[1] which is R.
Try this:
String name = "First Middle Last";
String[] data = name.split(" ");
String formatted = String.format("%s, %s %c.", data[2], data[0], data[1].charAt(0));
The last line assigns the value "Last, First M." to the variable formatted, as expected. This solution makes use of Java's Formatter class, which is a big help for all your string formatting needs.
You will need to first split the string (using String.split) and then format it.
Forgive me since I'm typing this on my iPad, the answer will look as follows:
String names = name.split("\\s+"); \\Split on whitespaces, including tab, newline and carriage return.
StringBuilder sb = new StringBuilder();
for (int x = 0; x < names.length; x++) {
switch (x) {
case 0: sb.apppend(names[names.length - 1]).append(", ");
break;
case 1: sb.append(names[0]).append(" ");
break;
case 2: sb.append(Character.toUpperCase(names[1].charAt(0))).append(".");
break;
default: break;
}
}
String fullName = sb.toString();
Related
I'm a student just starting out in Java; I get hung up on seemingly easy concepts and have had trouble finding the answer to this despite a lot of googling. The assignment asks to:
Prompt the user to enter the number of people
Create a String array of the given size
Prompt the user for the name of each person
Put each name in the String array you created
Use a Java for-each to print each name with the length of the name
The output should look something like:
"Person 1 is named Andrew, and their name is 6 characters long"
This is what I currently have coded.
System.out.print("Hello. Please enter the number of people: ");
int people = scan.nextInt();
String[] myPeople = new String[people + 1];
System.out.println("Enter the name of each person:");
for(int i = 0; i < myPeople.length; i++)
{
myPeople[i] = scan.nextLine();
}
for(String peoples : myPeople)
{
System.out.println(peoples);
}
As it stands right now, the program can collect input from the user, put it into an array, and then print the array back out.
Am I approaching this the wrong way? I can't think of how I would modify the last For to not just print all the names, and instead print out each one with the "Person X is named ... ", their name, and then the description of how many characters long their name is.
Read about string concatenation.
int j = 1;
for(String peoples : myPeople)
{
System.out.println("Person " + j + " is named " + peoples + " and their name is " + peoples.length() + " characters long");
j++;
}
+ operator is used for concatenation of the strings.
You are doing good. In last for loop you can just do something like:
int personNumber = 0;
for(String people: myPeople)
{
System.out.println(String.format("Person %d is named %s, and their name is %d characters long", personNumber + 1, people, people.length());
personNumber++;
}
And one thing I've noticed - why are you instantiating array using new String[people + 1]? Why this extra one person? Arrays indexes are numered from 0, so new String[5] would give you array of 5 persons.
Firstly, you should create an array of size people, not people + 1:
String[] myPeople = new String[people];
To produce output in the required the format, you need to use the + operator to join the strings together. Also, since the person's position in the array is required, you need to create a variable to store that:
int index = 1;
for (String person: myPeople) {
String output = "Person " + index + " is named " + person + ", and their name is " + person.length() + " characters long.";
System.out.println(output);
index++;
}
Alternatively, you can use print instead of println: (only showing code inside for loop)
System.out.print("Person ");
System.out.print(index);
System.out.print(" is named ");
System.out.print(person);
System.out.print(", and their name is ");
System.out.print(person.length());
System.out.println(" characters long.");
index++;
I have to do an assignment in my Java class using the Scanner method to input an integer (number of items), a string (name of the item), and a double (cost of the item). We have to use Scanner.nextLine() and then parse from there.
Example:
System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();
The user would input something like: 3 Captain Crunch 3.5
Output would be: Captain Crunch #3 for $10.5
The trouble I am having is parsing the int and double from the string, but also keeping the string value.
First of all, split the string and get an array.
Loop through the array.
Then you can try to parse those strings in array to their respective type.
For example:
In each iteration, see if it is integer. Following example checks the first element to be an integer.
string[0].matches("\\d+")
Or you can use try-catch as follow (not recommended though)
try{
int anInteger = Integer.parseInt(string[0]);
}catch(NumberFormatException e){
}
If I understand your question you could use String.indexOf(int) and String.lastIndexOf(int) like
String input = "3 Captain Crunch 3.5";
int fi = input.indexOf(' ');
int li = input.lastIndexOf(' ');
int itemNumber = Integer.parseInt(input.substring(0, fi));
double price = Double.parseDouble(input.substring(li + 1));
System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
itemNumber, itemNumber * price);
Output is
Captain Crunch #3 for $10.50
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();//take the message from the command line
String temp [] = message.split(" ");// assign to a temp array value
int number = Integer.parseInt(temp[0]);// take the first value from the message
String name = temp[1]; // second one is name.
Double price = Double.parseDouble(temp[2]); // third one is price
System.out.println(name + " #" + number + " for $ " + number*price ) ;
So I have this little program and all it needs to do is check if the last letter of the last name is an "s". And if it is an "s" itll change the last name to plural.
Ex.
Smith = Smith's
Smiths = Smiths'
Changes the last name to plural. Simple right? Seems so, but my if statement isnt detecting if the last letter is an "s"
Here's some code
import javax.swing.JOptionPane;
public class Lastname {
public static void main(String[] args) {
String messageText = null;
String title = null;
int messageType = 0;
String lastName = "";
String pluralLastName = "";
Input input;
input = new Input();
messageText = "Please enter a last name. I'll make it plural.";
title = "Plural Last Names";
messageType = 3;
lastName = input.getString(messageText,title,messageType);
int intLength = lastName.length();
String lastLetter = lastName.substring(intLength- 1);
System.out.println("The last letter is: " + lastLetter);
if (lastLetter.equals('s'))
JOptionPane.showMessageDialog(null, "The last name entered as plural is " + lastName + "'" );
else
JOptionPane.showMessageDialog(null, "The last name entered as plural is " + lastName + "'s" );
}}
The if statement always just adds an "'s" to everything.
You need to use double quotes to represent a String literal.
if (lastLetter.equals("s"))
Otherwise you are comparing a String with a Character which will always return false.
Instead of comparing Strings, you can compare chars:
char lastLetter = lastName.charAt(intLength- 1);
System.out.println("The last letter is: " + lastLetter);
if (lastLetter == 's')
Right now, you are comparing Strings to chars.
Here is SS of the whole question. http://prntscr.com/1dkn2e
it should work with any sentence not just the one given in the example
I know it has to do something with strings. Our professor has gone over with these string methods
http://prntscr.com/1dknco
This is only a basic java class so don't use any complicated stuff
here is what I have, don't know what to do after this
any help would be appreciated.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
}
}
You can use public String[] split(String regex):
splitted = sentence.split("\\s+");
splitted[0] Is the first word.
splitted[splitted.length - 1] Is the last word.
Since your'e not allowed to use String#split, you can do this trick:
myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord;
By doing this, you'll have a substring which contains the sentence without the last word. (For extracting the first word, you can use String#indexOf.
firstWord is the first word you extracted before (I'll not solve the whole problem for you, try to do it by yourself, it should be easy now)
Well as it seem your looking for very simple string arithmetic.
So that's the simplest i could do:
// get the index of the start of the second word
int index = line.indexOf (' ');
// get the first char of the second word
char c = line.charAt(index+1);
/* this is a bit ugly, yet necessary in order to convert the
* first char to upper case */
String start = String.valueOf(c).toUpperCase();
// adding the rest of the sentence
start += line.substring (index+2);
// adding space to this string because we cut it
start += " ";
// getting the first word of the setence
String end = line.substring (0 , index);
// print the string
System.out.println(start + end);
try this
String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);
Here is Another way you can do this.
UPDATED: Without Loops
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
int spacePosition = sentence.indexOf(" ");
String firstString = sentence.substring(0, spacePosition).trim();
String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
String firstChar = restOfSentence.substring(0, 1);
firstChar = firstChar.toUpperCase();
restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
System.out.println(restOfSentence + " " + firstString);
keyboard.close();
String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
String newname = last +" "+ first;
System.out.println(newname);
i want to take variables F and L and replace the lowercase first letters in last and first so they will be uppercase. How can I do this? i want to just replace the first letter in the last and first name with the char first and last
if you are trying to do what i think you are, you should consider using the apache commons-lang library, then look at:
WordUtils.capitalize
obviously, this is also open source, so for the best solution to your homework i'd take a look at the source code.
However, if i were writing it from scratch (and optimum performance wasn't the goal) here's how i would approach it:
public String capitalize(String input)
{
// 1. split on the negated 'word' matcher (regular expressions)
String[] words = input.toLowerCase().split("\\W");
StringBuffer end = new StringBuffer();
for (String word : words)
{
if (word.length == 0)
continue;
end.append(" ");
end.append(Character.toUpperCase(word.charAt(0)));
end.append(word.substring(1));
}
// delete the first space character
return end.deleteCharAt(0).toString();
}
While there's more efficient ways of doing this, you almost got it. You'd just need to concatenate the uppercase chars with the first and last name, bar the first character.
String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
EDIT:
You could also use a string tokenizer to get the names as in:
StringTokenizer st = new StringTokenizer(Name);
String fullName = "";
String currentName;
while (st.hasMoreTokens()) {
/* add spaces between each name */
if(fullName != "") fullName += " ";
currentName = st.nextToken();
fullName += currentName.substring(0,0).toUpperCase() + currentName.substring(1);
}
String name = "firstname lastname";
//match with letter in beginning or a letter after a space
Matcher matcher = Pattern.compile("^\\w| \\w").matcher(name);
StringBuffer b=new StringBuffer();
while(matcher.find())
matcher.appendReplacement(b,matcher.group().toUpperCase());
matcher.appendTail(b);
name=b.toString();//Modified Name