I want to make everything the user enters capitalized and certain letters to be replaced with numbers or symbols. Im trying to utilize .replace but something is not going right. Im not sure what im doing wrong?
public class Qbert
{
public static void main(String[] args)
{
//variables
String str;
//get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
//accept input
str = kb.nextLine();
System.out.print("" );
System.out.println(str.toUpperCase()//make all letters entered uppercase
//sort specific letters to make them corresponding number, letter, or symbol
+ str.replace("A,#")+ str.replaceChar("E","3")+ str.replaceChar ("G","6")
+ str.replaceChar("I","!")+ str.replaceChar("S","$")+ str.replaceChar ("T","7"));
}
}
In Java, Strings are immutable. This means that modifying a string will result in a new string. E.g.
str.replace("a", "b");
this will replace all the occurrences of 'a' to 'b' in a new string. Original string will remain unaffected. So, to apply the formatting on the actual string, we will have to write:
str = str.replace("a", "b");
Similarly, if we want to do multiple replacements then, we need to append replace calls together, e.g.
str = str.replace("a","b").replace("c", "d");
Going by this, if you want to perform the substitution, the last system.out in your code will be:
System.out.println(str.toUpperCase().replace("A","#").replace("E","3")
.replace("G","6").replace("I","!").replace("S","$").replace("T","7"));
String doesn't have a replaceChar method. You probably wanted to use method replace.
And String.replace() takes 2 arguments:
public String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab".
You have written str.replace("A,#")+... instead of str.replace("A","#")+..., and so on
One more thing - use a good IDE like Eclipse or Intellij IDEA, they will highlight the parts of your code where you have errors.
public static void main(String... args) {
// variables
String str;
// get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
// accept input
str = kb.nextLine();
System.out.print("");
System.out.println(str.toUpperCase()); // Upper Case
System.out.println(str.toUpperCase().replace("A", "#").replace("E", "3")
.replace("E", "3").replace("G", "6").replace("I", "!").replace("S", "$").replace("T", "7") );
}
This should work like you want it to. Hope you find this helpful.
As you want to make multiple changes to the same string, you just use
str.toUpperCase().replace().replace().... This means you are giving
the output of str.toUpperCase() to the first replace function and so
on...
System.out.println(str.toUpperCase()
.replace("A","#")
.replace("E","3")
.replace("G","6")
.replace("I","!")
.replace("S","$")
.replace("T","7"));
Related
This program is to return the readable string for the given morse code.
class MorseCode{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String morseCode = scanner.nextLine();
System.out.println(getMorse(morseCode));
}
private static String getMorse(String morseCode){
StringBuilder res = new StringBuilder();
String characters = new String(morseCode);
String[] charactersArray = characters.split(" "); /*this method isn't
working for
splitting what
should I do*/
for(String charac : charactersArray)
res.append(get(charac)); /*this will return a string for the
corresponding string and it will
appended*/
return res.toString();
}
Can you people suggest a way to split up the string with multiple whitespaces. And can you give me some example for some other split operations.
Could you please share here the example of source string and the result?
Sharing this will help to understand the root cause.
By the way this code just works fine
String source = "a b c d";
String[] result = source.split(" ");
for (String s : result) {
System.out.println(s);
}
The code above prints out:
a
b
c
d
First, that method will only work if you have a specific number of spaces that you want to split by. You must also make sure that the argument on the split method is equal to the number of spaces you want to split by.
If, however, you want to split by any number of spaces, a smart way to do that would be trimming the string first (that removes all trailing whitespace), and then splitting by a single space:
charactersArray = characters.trim().split(" ");
Also, I don't understand the point of creating the characters string. Strings are immutable so there's nothing wrong with doing String characters = morseCode. Even then, I don't see the point of the new string. Why not just name your parameter characters and be done with it?
Hello everyone im trying to make a code to remove
vowels and consonants when a user types a string
but i seem to fail at the code and i need to use a stack class to do it
Sample Output should be like this and will ignore non alphabet characters
Enter a String : hello1234!##$
Vowels : eo
Consonant : hll
Final contents : 1234!##$
can someone fix my code
this is the error I get
enter image description here
import java.util.Scanner;
import java.util.Stack;
public class PushPop
{
//I used the push and pop methods
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String str = sc.nextLine();
Stack<String> String = new Stack();
String.push(str);
String vowels = String.pop();
vowels = vowels.replace("[aeiou]", "");
String consonants = String.pop();
consonants = consonants.replace("[qbcdfghjklmnpqrstvwxyz]", "");
System.out.println("Vowels: "+ vowels);
System.out.print("Consonant: "+ consonants);
//this will print what is left after popping the elements
System.out.print("Final contents: "+ str);
}
}
If you just want to remove all vowels and consonants form the user's input, a Stack is not needed (at least if you use the ready made Java's Pattern in some way). In fact, you get the Exception because you try to pop from the Stack twice, while having only pushed once. In particular you first push the user's input str, then pop it to the variable vowels (so the Stack is now empty) and then you pop from it again, this time into the variable consonants.
vowels = vowels.replace("[aeiou]", "");
According to documentation of replace it will replace all literals with the second argument. This means that it will replace all Strings matching the literal "[aeiou]" (if it exists as is in the user's input) with the empty String. Instead you should use replaceAll method which takes a regex (ie Regular Expression) as the first argument:
str = str.replaceAll("[aeiou]", "");
The regular expressions you are using seem correct for your problem, although you want to first remove the vowels from the user's input and then from that String (which is the result of the user's input by removing all vowels) remove also the consonants. So the logic should instead be:
String str = sc.nextLine(); //Get user input.
str = str.replaceAll("[aeiou]", ""); //Remove vowels.
str = str.replaceAll("[qbcdfghjklmnpqrstvwxyz]", ""); //Remove consonants.
System.out.println(str); //Print result.
which, if you combine the two regexes toghether in a single operation, can be shortened to:
String str = sc.nextLine();
str = str.replaceAll("[aeiouqbcdfghjklmnpqrstvwxyz]", "");
System.out.println(str);
which, if you realize that these are all alphabet letters, can be shortened even further with:
str = str.replaceAll("[a-z]", "");
and if you also want both upper and lower case letters, then you can do:
str = str.replaceAll("[a-zA-Z]", "");
which is equivalent to:
str = str.replaceAll("\\p{Alpha}", "");
All those examples can be made clear for someone if they read the documentation on how a Java Pattern is constructed, so it may help to take a look there, if you didn't already know it.
i need to use a stack class to do it
Can you please explain what is the desired behaviour, and how a Stack needs to be used? Because it seems like you just want to remove all alphabet letters. Are you required to not use regexes for this?
I have been trying for a while to make a method which takes an user input and changes it so that potential spaces infront and after the text should be removed. I tried .trim() but doesnt seem to work on input strings with two words. also I didnt manage to make both first and second word have the first letter as Capital.
If user inputs the following string I want all separate words to have all small letters except for the first in the word. e.g: Long Jump
so if user inputs:
"LONG JuMP"
or
" LoNg JUMP "
change it to
"Long Jump"
private String normalisera(String s) {
return s.trim().substring(0,1).toUpperCase() + s.substring(1).toLowerCase();
}
I tried the method above but didnt work with two words, only if the input was one. It should work with both
To remove all spaces extra spaces you can do something like this
string = string.trim().replaceAll(" +", " ");
The above code will call trim to get rid of the spaces at the start and end, then use regex to replace everything that has 2 or more spaces with a single space.
To capitalize the first word, if you're using Apache's commons-lang, you can use WordUtils.capitalizeFully. Otherwise, you'll need to use a homebrewed solution.
Simply iterate through the String, and if the current character is a space, mark the next character to be uppercased. Otherwise, make it lowercase.
Split your problems into smaller ones:
You need to be able to:
iterate over all words and ignore all whitespaces (you can use Scanner#next for that)
edit single word into new form (create helper method like String changeWord(String){...})
create new String which will collect edited versions of each word (you can use StringBuilder or better StringJoiner with delimiter set as one space)
So your general solution can look something like:
public static String changeWord(String word) {
//code similar to your current solution
}
public static String changeText(String text) {
StringJoiner sj = new StringJoiner(" ");// space will be delimiter
try(Scanner sc = new Scanner(text)){
while (sc.hasNext()) {
sj.add(changeWord(sc.next()));
}
}
return sj.toString();
}
Since Strings are immutable and you cannot make in place changes you need to store it in a separate variable and then do your manipulations like this:
String s = " some output ";
String sTrimmed = s.trim();
System.out.println(s);
System.out.println(sTrimmed);
Change your code like this for the rest of your code as well.
import java.util.*;
import java.io.*;
public class OptimusPrime{
public static void main(String[] args){
System.out.println("Please enter the sentence");
Scanner scan= new Scanner(System.in);
String bucky=scan.nextLine();
int pOs=bucky.indexOf("is");
System.out.println(pOs);
if(pOs==-1){
System.out.println("the statement is invalid for the question");
}
else{
String nay=bucky.replace("is", "was");
System.out.println(nay);
}
}
}
Now I know the "replace" method is wrong as i want to change the particular string "is" and not the portion of other string elements. I also tried using SetChar method but I guess the "string is immutable" concept applies here.
How to go about it?
Using String.replaceAll() instead enables you to use a regex. You can use the predefined character class \W in order to catch a non-word character :
System.out.println("This is not difficult".replaceAll("\\Wis", ""));
Output :
This not difficult
The verb is disappeared but not the isfrom This.
Note 1 : It also removes the non-word character. If you want to keep it, you can capture it with some parenthesis in the regex then reintroduce it with $1:
System.out.println("This [is not difficult".replaceAll("(\\W)is", "$1"));
Output :
This [ not difficult
Note 2 : If you want to handle a string which begins with is, this line will not be enough but it is quite easy to handle with another regex.
System.out.println("is not difficult".replaceAll("^is", ""));
Output :
not difficult
If you use replaceAll instead, then you can use \b to use the word boundary to perform a "whole words only" search.
See this example:
public static void main(final String... args) {
System.out.println(replace("this is great", "is", "was"));
System.out.println(replace("crysis", "is", "was"));
System.out.println(replace("island", "is", "was"));
System.out.println(replace("is it great?", "is", "was"));
}
private static String replace(final String source, final String replace, final String with) {
return source.replaceAll("\\b" + replace + "\\b", with);
}
The output is:
this was great
crysis
island
was it great?
Simpler way:
String nay = bucky.replaceAll(" is ", " was ");
Match word boundary:
String nay = bucky.replaceAll("\\bis\\b", "was");
to replace string with another string you can use this
if Your string variable contains like this
bucky ="Android is my friend";
Then you can do like this
bucky =bucky.replace("is","are");
and your bucky's data will be like this Android are my friend
Hope this helps you.
Example:
String t;
String j ="j2se";
Scanner sc =new Scanner(System.in);
System.out.println("enter the search key:");
t=sc.next();
if (j.contains(t))
{
System.out.println("yes");
}
else System.out.println("no");
If the user enters 'j2', 'se' or 'j2s' as an input the output is 'yes'. If the input is 'jse' the output is 'no'.
Is there a method to ignore the number stored in string search like ignoring upper or lower case letters?
Why you don't juste create a copy of this string with no numeric inside ?
And after juste compare this new string with your array ?
Like :
String stringWithoutNumber = j.replaceAll("\\d+","");
stringWithoutNumber.contains(t);
Many of programs have a function called sanitize which clean the url or string before the comparaison.
Hope it's help
-- EDIT --
You don't need to put the + in \\d+ because the method replaceAll replace all the digit. But it's more efficient because it makes less replacement.
use replaceAll("\\d+","") on the String and then compare.
This removes all the numbers from your String. Now you could use this new String and compare.
or use :
\\W+ // replaces everything apart from characters .