Turn some alphabet to specific number in Java Netbeans - java

i want to make program that will turn your input text into another version.
For example like this:
If I input = "I want some coffee" , it will turn to = " 1 W4NT S0M3 C0FF33".
From this example we get that =
A will turn to 4, O will turn to 0, E will turn to 3, and I will turn to 1.
So, what code to make this program? i'm sorry i'm so noob in java.
Thank you.

There are two methods. Convert the String to uppercase(if needed). Then run a loop to iterate through the characters of the string. If the character is A,E,I,O, then add 4,3,1,0 to the string s2 else add the current character. (s1="I want some coffee").
String s1="I want some coffee";
s1=s1.toUpperCase();
String s2="";
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
if(ch=='A'||ch=='a')
s2+="4";
else if(ch=='O'||ch=='o')
s2+="0";
else if(ch=='E'||ch=='e')
s2+="3";;
else if(ch=='I'||ch=='i')
s2+="1";
else
s2+=ch;
}
System.out.println(s2);
Or, you can use replaceAll() method to replace all the occurences of A,E,I,O with 4,3,1,0.
public static void main(String[] args) {
String s1="I want some coffee";
s1=s1.toUpperCase();
s1=s1.replaceAll("A","4");
s1=s1.replaceAll("E","3");
s1=s1.replaceAll("I","1");
s1=s1.replaceAll("O","0");
System.out.println(s1);
}
}

Related

How to make spaced text .equal() to unspaced text

I am working on code that takes two inputs like the following:
,Air Condition,
, Air Condition,
This text is received from a JSON object and the commas are something that must be considered.
As can be seen, one has white space at the beginning and the other doesn't. How can I compare them using the equals()?
So far, I have used the following code to compare the two strings:
if (oldSelected.get(i).equalsIgnoreCase(String.valueOf(fc.getText()))){
fc.setChecked(true);
}
However, it doesn't do what I expect it to do.
How i can trim this space and get the desired results?
You need to trim the white spaces first.
String oldSelected = ",Air Conditioner,";
String newSelected = ", Air Conditioner, ";
if(oldSelected.replaceAll("\\s", "").equalsIgnoreCase(newSelected.replaceAll("\\s", ""))){
// Do Something
}
else{ // Do Something Else
}
Hope that helps! :)
You can do something like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s1.equals(s2.replace(", ", ",")));
}
or, if you want to keep space between words, you may use like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s2.split(", ")[1]);
System.out.println(s1.split(",")[1]);
System.out.println(s1.split(",")[1].equals(s2.split(", ")[1]));
}
Try,
String.valueOf(fc.getText())).replaceAll("\\s+","")
This removes all whitespaces and non-visible characters (e.g. tab, \n)
you can use String methot called SPLIT for example you have
String STR1 = "Ahoj"
String STR2 = "Ahoj "
String x[] = STR1.split(" ");
String y[] = STR2.split(" ");
then use simple for loop to check all words :)
Well, worked solution as #Rahul suggest to use .trim() but this worked with english words only, so in order to equalize all language i trim the equalized text to as below :
String checkedVal = oldSelected.get(i);
checkedVal = checkedVal.trim();
if (checkedVal.equalsIgnoreCase(String.valueOf(fc.getText().toString().trim()))){
fc.setChecked(true);
}
Thanks for all answers.

String.replace isn't working

import java.util.Scanner;
public class CashSplitter {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
System.out.println("Cash Values");
String i = S.nextLine();
for(int b = 0;b<i.length(); b ++){
System.out.println(b);
System.out.println(i.substring(0,i.indexOf('.')+3));
i.replace(i.substring(0, i.indexOf('.') + 3), "");
System.out.println(i);
System.out.println(i.substring(0, i.indexOf('.') + 3));
}
}
}
The code should be able to take a string with multiple cash values and split them up, into individual values. For example 7.32869.32 should split out 7.32, 869.32 etc
A string is immutable, therefore replace returns a new String for you to use
try
i = i.replace(i.substring(0, i.indexOf('.') + 3), "");
Although try using
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
There are several problems with your code:
You want to add two, not three, to the index of the decimal point,
You cannot use replace without assigning back to the string,
Your code assumes that there are no identical cash values.
For the last point, if you start with 2.222.222.22, you would get only one cash value instead of three, because replace would drop all three matches.
Java offers a nice way of splitting a String on a regex:
String[] parts = S.split("(?<=[.]..)")
Demo.
The regex is a look-behind that expects a dot followed by any two characters.

How to print out all permutations of a string in Java

Given a string, I need to print out all permutations of the string. How should I do that? I have tried
for(int i = 0; i<word.length();i++)
{
for(int j='a';j<='z';j++){
word = word.charAt(i)+""+(char)j;
System.out.println(word);
}
}
Is there a good way about doing this?
I'm not 100% sure that I understand what you are trying to do. I'm going to go by your original wording of the question and your comment to #ErstwhileIII's answer, which make me think that it's not really "permutations" (i.e. rearrangement of the letters in the word) that you are looking for, but rather possible single-letter modifications (not sure what a better word for this would be either), like this:
Take a word like "hello" and print a list of all "versions" you can get by adding one "typo" to it:
hello -> aello, bello, cello, ..., zello, hallo, hbllo, hcllo, ..., hzllo, healo, heblo, ...
If that's indeed what you're looking for, the following code will do that for you pretty efficiently:
public void process(String word) {
// Convert word to array of letters
char[] letters = word.toCharArray();
// Run through all positions in the word
for (int pos=0; pos<letters.length; pos++) {
// Run through all letters for the current position
for (char letter='a'; letter<='z'; letter++) {
// Replace the letter
letters[pos] = letter;
// Re-create a string and print it out
System.out.println(new String(letters));
}
// Set the current letter back to what it was
letters[pos] = word.charAt(pos);
}
}
OH .. to print out all permutations of a string, consider your algorithm first. What is the definition of "all permutations" .. for example:
String "a" would have answer a only
String "ab" would have answer: ab, ba
String "abc" would have answer: abc acb, bca, bac, cba, cab
Reflect on the algorithm you would use (write it down in english) .. then translate to Java code
While not the most efficient, a recursive solution might be easiest to use (i.e. for a string of length n, go through each of the characters and follow that with the permutations of the string with that character removed).
EDIT: Ok... you changed your request. Permutations is a whole other story. I think this will help: Generating all permutations of a given string
Not sure what you are trying to do... Example 1 is to get the alphabet one letter next to another. Example 2 is to print whatever you gave us there as an example.
//Example 1
String word=""; //empty string
for(int i = 65; i<=90;i++){ //65-90 are the Ascii numbers for capital letters
word+=(char)i; //cast int to char
}
System.out.println(word);
//Example 2
String word="";
for (int i=65;i<=90;i++){
word+=(char)i+"rse";
if(i!=90){ //you don't want this at the end of your sentence i suppose :)
word+=", ";
}
}
System.out.println(word);

how to replace some chars in the string with other chars by the user?

I wrote a text, and i want to change some chars to any other chars which the user will choosing them, I tried and couldn't find the correct answer, so please guide me.
the code in the MyTest Class is:
public String replace(String input,char from,char to){
String input2 ="";
String input3="";
this.input=input3;
for(int i=0;i<input.length();i++){
for(int j=0;j<input3.length();j++){
if(input.charAt(i)==input3.charAt(j)){
input2=input3.replace(from, to);
System.out.println(input2);
}
}
}
return input2;
}
And the code in the Main Class:
System.out.println("please enter the new character: ");
char c1 = scan.next().charAt(0);
System.out.println("Please choose the letters that you want to change it which in the text:");
String ltr = scan.next();
obj1.convertChars(ltr, c1);
(1) What you should do:
There is a simple method for what you are after: String#replace(char,char):
String replaced = myString.replace(from,to);
(2) Why your code fails:
Note you are iterating and trying to invoke replace() on input3, while it is an empty string! you never changed it! effectively your method do nothing (except assigning the instance variable input. Definetly not what you wanted.
(3) Also important: Strings in java are immutable
In java, String is immutable - so what you are doing is actually crating a new string with replaced characters, and NOT replacing the characters in the same string object!
Changing the String is not as simple, and should be avoided, but can be done using the reflection API.
What you want to do shouldn't even be a method. Here's why:
public String replace(String input,char from,char to){
return input.replace(from, to);
}
Thus kind of method adds no value - you should just call the replace() method of String directly.
The question seemed a bit unclear. I hope you want a function like this:
Call this function from the main function. Pass the string "abcde", 'a', 'x'. It will return you "xbcde".
public String replace(String inputStr, char from, char to){
StringBuffer newString=new StringBuffer();
for(int i=0;i<inputStr.length();i++){
if(inputStr.charAt(i)==from){
newString.append(to);
}
else{
newString.append(inputStr.charAt(i));
}
}
return newString.toString();
}

How can I extract the numbers from a string only using charAt(), length() and/or toCharArray() in Java

I have to do this for an assignment in my java class. I have been searching for a while now, but only find solutions with regex etc.
For my assignment however I may only use charAt(), length() and/or toCharArray(). I need to get from a string like gu578si300 for example just the numbers so it will become: 578300.
i know numbers are 48 - 57 in ASCII but i can't figure out how to do this in java. You guys any ideas?
i was thinking about a for loop that checks whether the (int) char is between 48-57 en if so puts the value into a seperate array. Howeevr i dont know how to programm that last thing.
I now have this;
public static String filterGetallenreeks(String reeks){
String temp = "";
for (char c : reeks.toCharArray()) {
if ((int) c > 47 && (int) c < 58)
temp += c;
}
return temp;
however it is not working, it just outputs the same as goes in.
is it something in my mainm which looks like this. If i'm right the return temp; will return the temp string into the reeks string in the main right? why is my input still the same a sthe output?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Voer een zin, woord of cijferreeks in:");
String reeks = sc.nextLine();
if (isGetallenreeks(reeks)){
System.out.println("is getallenreeks");
filterGetallenreeks(reeks);
System.out.println(reeks);
}
Since this is homework I will not be providing the complete solution, however, this is how you should go about it:
Do a for loop that iterates for the total amount of characters within the string (.length). Check if the character is a digit using the charAt and isDigit methods.
You could do a loop that checks a character in the string, and if it's a number, append it to another string:
//I haven't tested this, so you know.
String test = "gu578si300 ";
String numbers = "";
for(int i=0; i<test.length(); i++){
if("0123456789".indexOf(test.charAt(i)) // if the character at position i is a number,
numbers = numbers + test.charAt(i); // Add it to the end of "numbers".
}
int final = Integer.parseInt(numbers); // If you need to do something with those numbers,
// Parse it.
Let me know if that works for you.
It seems like a reasonable approach, but I'd make a couple of changes from what you suggested:
If you need to result as a string then use a StringBuilder instead of an array.
Use character literals like '0' and '9' instead of ASCII codes to make your code more readable.
Update
The specific problem with your code is this line:
temp = temp + (int)c;
This converts the character to its ASCII value and then converts that to a decimal string containing the ASCII value. That's not what you want. Use this instead:
temp += c;

Categories