I don't really know how to explain the problem. I do have a scanner imported after the package. I'm not sure if you can stack methods, and if you can I'm definitely doing it wrong.
Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = console.next();
name.trim();
name.toUpperCase(name.substring(name.charAt(name.indexOf(" "))));
System.out.println("Your name is: " + name);
Just split the String into the first word and second word based on the indexOf(" ")
Capitalize the second word using toUpperCase
Concatenate both words together using +
name = name.substring(0, name.indexOf(" ")) + name.substring(name.indexOf(" ")).toUpperCase();
Note: Not sure if you are required to handle invalid input, but this code would only work assuming a valid two-word name is entered, with a space in-between
Also, make sure to change console.next() to console.nextLine() to ensure you retrieve the entire line of input
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = console.nextLine();
String[] words = name.split(" ");
words[1] = capitalizeWord(words[1]);
name = String.join(" ", words);
System.out.println("Your name is: " + name);
}
private static String capitalizeWord(String s) {
s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
return s;
}
At first you split the input into a String array. Then you replace the first character of the 2nd (index 1) element and join the array back to a String.
Input: john doe, Output: john Doe
String is immutable in java so if you want to "change" a Strig variable value, you need to reassign it to itself. I think a good approach to prepare more than 2 input, many people has middle name e.g.
This function split the input into parts then make the first letter uppercase then return the whole name after concat them with space.
public String capitalizeName(String name) {
String[] nameParts = name.split(" ");
for (int i = 0; i < nameParts.length; i++) {
nameParts[i] = nameParts[i].substring(0, 1).toUpperCase() + nameParts[i].substring(1);
}
return String.join(" ", nameParts);
}
String is immutable in Java.
BE SIMPLE!!!
public static void main(String... args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your first name and last name: ");
String firstName = upperCaseFirstLetter(scan.next().trim());
String lastName = upperCaseFirstLetter(scan.next().trim());
System.out.println("Your name first name: " + firstName);
System.out.println("Your name last name: " + lastName);
}
private static String upperCaseFirstLetter(String name) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
One solution would be to make the String a String array using the split(regex)-method. It will split up a string into a String array, breaking them up at regex.
For example:
String text = "This is a text.";
String textArray = text.split(" ");
for(String element : textArray)
{
System.out.println(element);
}
will print
This
is
a
text.
If you got a String[] like that, you can choose the second String (index 1 of array) and capitalize it. You can do so in a foreach loop, for example.
String text = "This is a text.";
text = text.trim(); // if you want to trim it.
String[] textArray = text.split(" ");
String newText = "";
int index = 0;
for(String element : textArray)
{
if(index == 1)
{
element = element.toUpperCase();
}
newText = newText + element + " ";
index++;
}
System.out.println(newText);
If you want to handle errors, you can put in in a try-catch-block like this.
try
{
[Your code]
}
catch (Exception e)
{
System.out.println("An error occured.");
}
This is, of course, not a very short way to do it. However, it's easy to understand and it can handle even a string consisting of several words.
Related
I am attempting to write a program that reverses a string's order, even the punctuation. But when my backwards string prints. The punctuation mark at the end of the last word stays at the end of the word instead of being treated as an individual character.
How can I split the end punctuation mark from the last word so I can move it around?
For example:
When I type in : Hello my name is jason!
I want: !jason is name my Hello
instead I get: jason! is name my Hello
import java.util.*;
class Ideone
{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String input = userInput.nextLine();
String[] sentence= input.split(" ");
String backwards = "";
for (int i = sentence.length - 1; i >= 0; i--) {
backwards += sentence[i] + " ";
}
System.out.print(input + "\n");
System.out.print(backwards);
}
}
Manually rearranging Strings tends to become complicated in no time. It's usually better (if possible) to code what you want to do, not how you want to do it.
String input = "Hello my name is jason! Nice to meet you. What's your name?";
// this is *what* you want to do, part 1:
// split the input at each ' ', '.', '?' and '!', keep delimiter tokens
StringTokenizer st = new StringTokenizer(input, " .?!", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
String token = st.nextToken();
// *what* you want to do, part 2:
// add each token to the start of the string
sb.insert(0, token);
}
String backwards = sb.toString();
System.out.print(input + "\n");
System.out.print(backwards);
Output:
Hello my name is jason! Nice to meet you. What's your name?
?name your What's .you meet to Nice !jason is name my Hello
This will be a lot easier to understand for the next person working on that piece of code, or your future self.
This assumes that you want to move every punctuation char. If you only want the one at the end of the input string, you'd have to cut it off the input, do the reordering, and finally place it at the start of the string:
String punctuation = "";
String input = "Hello my name is jason! Nice to meet you. What's your name?";
System.out.print(input + "\n");
if(input.substring(input.length() -1).matches("[.!?]")) {
punctuation = input.substring(input.length() -1);
input = input.substring(0, input.length() -1);
}
StringTokenizer st = new StringTokenizer(input, " ", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
sb.insert(0, st.nextToken());
}
sb.insert(0, punctuation);
System.out.print(sb);
Output:
Hello my name is jason! Nice to meet you. What's your name?
?name your What's you. meet to Nice jason! is name my Hello
Like the other answers, need to separate out the punctuation first, and then reorder the words and finally place the punctuation at the beginning.
You could take advantage of String.join() and Collections.reverse(), String.endsWith() for a simpler answer...
String input = "Hello my name is jason!";
String punctuation = "";
if (input.endsWith("?") || input.endsWith("!")) {
punctuation = input.substring(input.length() - 1, input.length());
input = input.substring(0, input.length() - 1);
}
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String reordered = punctuation + String.join(" ", words);
System.out.println(reordered);
The below code should work for you
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceSample {
public static void main(String[] args) {
String originalString = "TestStr?";
String updatedString = "";
String regex = "end\\p{Punct}+|\\p{Punct}+$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(originalString);
while (matcher.find()) {
int start = matcher.start();
updatedString = matcher.group() + originalString.substring(0, start);<br>
}
System.out.println("Original -->" + originalString + "\nReplaced -->" + updatedString);
}
}
You need to follow the below steps:
(1) Check for the ! character in the input
(2) If input contains ! then prefix it to the empty output string variable
(3) If input does not contain ! then create empty output string variable
(4) Split the input string and iterate in reverse order (you are already doing this)
You can refer the below code:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String originalInput = userInput.nextLine();
String backwards = "";
String input = originalInput;
//Define your punctuation chars into an array
char[] punctuationChars = {'!', '?' , '.'};
String backwards = "";
//Remove ! from the input
for(int i=0;i<punctuationChars.length;i++) {
if(input.charAt(input.length()-1) == punctuationChars[i]) {
input = input.substring(0, input.length()-1);
backwards = punctuationChars[i]+"";
break;
}
}
String[] sentence= input.split(" ");
for (int i = sentence.length - 1; i >= 0; i--) {
backwards += sentence[i] + " ";
}
System.out.print(originalInput + "\n");
System.out.print(input + "\n");
System.out.print(backwards);
}
Don't split by spaces; split by word boundaries. Then you don't need to care about punctuation or even putting spaces back, because you just reverse them too!
And it's only 1 line:
Arrays.stream(input.split("\\b"))
.reduce((a, b) -> b + a)
.ifPresent(System.out::println);
See live demo.
I want to prepend "\n" to the last word of the string
for example
Hello friends 123
Here i want to add "\n" just before the word "123"
I tried below code but having no idea what to do now
String sentence = "I am Mahesh 123"
String[] parts = sentence.split(" ");
String lastWord = "\n" + parts[parts.length - 1];
Try this
String sentence = "Hello friends 123456";
String[] parts = sentence.split(" ");
parts[parts.length - 1] = "\n" + parts[parts.length - 1];
StringBuilder builder = new StringBuilder();
for (String part : parts) {
builder.append(part);
builder.append(" ");
}
System.out.println(builder.toString());
Output will be :~
Hello friends
123456
Try the below code...it will work
parts[parts.length]=parts[parts.length-1];
parts[parts.length-1]="\n";
Please try this.
String sentence = "I am Mahesh 123";
String[] parts = sentence.split(" ");
String string="";
for (int i =0;i<parts.length;i++)
{
if (i==parts.length-1)
{
string = string+"\n"+parts[i];
}
else
string = string+" "+parts[i];
}
Toast.makeText(Help.this, string, Toast.LENGTH_SHORT).show();
You want to add a break/new line at the end of your string.
You can find the space via lastIndexOf(), this will give you the int of where the space is located in the String sentence.
You can use this small example here:
public class Main {
public static void main(String[] args) {
String sentence = "I am Mahesh 123";
int locationOfLastSpace = sentence.lastIndexOf(' ');
String result = sentence.substring(0, locationOfLastSpace) //before the last word
+ "\n"
+ sentence.substring(locationOfLastSpace).trim(); //the last word, trim just removes the spaces
System.out.println(result);
}
}
Note that StringBuilder is not used because since Java 1.6 the compiler will create s StringBuilder for you
I wrote a little program that prompts a user to enter their first middle and last name I then attempt to locate each white space and store the name that comes after the whitespace into a new String variable.
Problem: I want to locate the white spaces before each part of the name so that I can take each relative name and store it in a new String variable but i'm not sure where I'm going wrong.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name = "",
firstName = "",
middleName = "",
lastName = "";
boolean isName = false;
while(!isName)
{
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
if(name.length() < 0)
{
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
System.out.print("Invalid input");
}
else isName = true;
}
for(int j = 0; j < name.length(); j++)
{
if(name.charAt(j) == ' ')
{
firstName = name.substring(0, j); // Start at 0 end at first white space
middleName = name.substring(j + 1, name.length());
lastName = name.substring(j + 1, name.length());
}
}
System.out.println("\nLast Name, First Name, Middle Name: " + lastName + firstName + middleName );
}
}
The output I'm getting looks like this
Enter your name as 'First Middle Last': Adam Thomas Smith
Last Name, First Name, Middle Name: SmithAdam ThomasSmith
Any suggestions as to how to fix this?
name = name.trim(); // To avoid suprises, as Pshemo suggested.
String[] splitName = name.split("\\s+");
System.out.println("\nLast Name, First Name, Middle Name: "
+ splitName[2] + " " + splitName[0] + " " + splitName[1]);
Try this instead. It uses String.split() to split the name on a space (\\s+, a regex) and returns the values as an array. The names could also be assigned to a variable if you choose.
You can try the following code, just by splitting the 'name' variable on each space into an String[] Then by getting each value from the array and assigning to the value you wish.
String[] str = name.split(" ");
firstName = str[0];
middleName = str[1];
lastName = str[2];
Better to use split(" ") function... It will change you string to an string array. Eg:-
String names = "Madan mohan malviya";
String arr[] = name.split(" ");
for( name :names){
System.out.println(name); // print each string content
}
public class Registration {
public static void main(String[] args) {
final String MY_DELIMITER = "','";
boolean tryAgain = true;
String fName = "";
String A = fName.substring(0,2);
String lName = "";
int lNameLength = lName.length();
String B = lName.substring(lNameLength-4,lNameLength);
String address = "";
String zip = "";
String C = zip.substring(0,5);
String age = "";
String D = age.substring(0,1);
String gender = "";
String race = "";
String regList = "";
Scanner myScanner = new Scanner(System.in);
boolean showList = false;
// Get input from the user until they type "q"
// For each input check for "q"
// if not q, append the input
// to the existing String + the delimiter
while(tryAgain)
{
System.out.println("Name: (q to quit)");
fName = myScanner.nextLine();
System.out.println("Last Name: (q to quit)");
lName = myScanner.nextLine();
System.out.println("Addess: ");
address = myScanner.nextLine();
System.out.println("Age: ");
age = myScanner.nextLine();
System.out.println("Gender: ");
gender = myScanner.nextLine();
System.out.println("Race: ");
race = myScanner.nextLine();
if(fName.equals("q"))
{
tryAgain = false;
}
else
{
// Append new name to the list using a delimiter
regList = fName + lName + "\n" + address + "\n" + age + "\n" + gender + "\n" + race + MY_DELIMITER;
}
} // end of while( )
System.out.println("Here is your registration:" + regList);
// Convert the String into an array, using the same delimiter
String[ ] regArray = regList.split(MY_DELIMITER);
// Ask the user if they want to display the contents of the array
// If "y" then display the list using a foreach loop
System.out.println("Would you like to see the registration from the Array? [y-n]");
fName = myScanner.nextLine( );
myScanner.close();
fName = fName.toLowerCase( );
showList = fName.equals("y")?true:false;
if(showList)
{
// Display the results using for each
System.out.println("Here is your registration from the array: ");
// Use a for each statement instead of the more complex for( ) loop
// for(int counter=0; counter < employeeArray.length; counter++)
for(String thisReg:regArray)
{
System.out.println(thisReg);
System.out.printf("USER ID: ", A + "-" + B + "-" + C + "-" + D);
}
} // end of if(showList)
}
}
I am trying to extract out the first 3 letters of the fName input, so I figured I could use fName.substring to do that, but it gives me this error.
Sorry I didn't add all of my code, to save time. Apparently it looked confusing. Any way so the fName input is the name of the user. Can it not be in that order?
Erm...your sequence of operations is suspect. Everywhere, actually.
Look at the following interaction:
String fName = "";
String A = fName.substring(0,2);
You declare an empty string, then immediately take the substring of it. Where are you getting the data for the substring from? There's nothing to substring here - the empty string has a length of zero.
You should be certain that you're putting data into your string before taking a substring of it. Using a Scanner would go a long way here.
Or better yet, moving your instance of myScanner at the top of main would make it much clearer as to where that's supposed to go, and how it's supposed to work.
Always check the length of string before substring anything. Especially when a user is giving you this variable.
You are trying to get a substring of an empty string.
String fName = "";
String A = fName.substring(0,2); // here fName is empty!!!
Change fName into some actual String and also check for length of the String before calling substring to make sure substring of the size you want exists.
String fName = "somestring";
if(fName.length() >= 2) {
String A = fName.substring(0,2);
System.out.println(A); // prints out "so"
}
That is the case with all of your other Strings as well.
The objective is to get a sentence input from the user, tokenize it, and then give information about the first three words only (word itself, length, and then average the first 3 word lengths). I'm not sure how to turn the tokens into strings. I just need some guidance - not sure how to proceed. I've got this so far:
public static void main(String[] args) {
String delim = " ";
String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");
StringTokenizer tk = new StringTokenizer(inSentence, delim);
int sentenceCount = tk.countTokens();
// Output
String out = "";
out = out + "Total number of words in the sentence: " +sentenceCount +"\n";
JOptionPane.showMessageDialog(null, out);
}
I'd really appreciate any guidance!
If you just wanted to get the first 3 tokens, then you could do something like this:
String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";
From there should be pretty easy to calculate the other requirements
public static void main(String[] args) {
String delim = " ";
String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");
StringTokenizer tk = new StringTokenizer(inSentence, delim);
int sentenceCount = tk.countTokens();
// Output
String out = "";
out = out + "Total number of words in the sentence: " +sentenceCount +"\n";
JOptionPane.showMessageDialog(null, out);
int totalLength = 0;
while(tk.hasMoreTokens()){
String token = tk.nextToken();
totalLength+= token.length();
out = "Word: " + token + " Length:" + token.length();
JOptionPane.showMessageDialog(null, out);
}
out = "Average word Length = " + (totalLength/3);
JOptionPane.showMessageDialog(null, out);
}
The way to get the individual strings by using nextToken().
while (tk.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You're free to do anything else than printing them, of course. If you only want the three first tokens, you might not want to use a while loop but a couple of simple if statements.