I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield
Related
I am trying to replace even incidences in a string with their ASCII value. I'm using the StringBuilder replace method, starting at the index per iteration, ending at the same index, and replacing the value with the ASCII value. For some reason the replace method is not replacing the element at the index with the ASCII value.
sb is my StringBuilder holding the string; result is my desired returned string.
for (int i =0; i < sb.length(); i=i+2) {
char c = sb.charAt(i);
int n = c;
String a = String.valueOf(n);
sb.replace(sb.charAt(i), sb.charAt(i), a);
result = sb.toString();
}
Some things I will correct, but #Nikolai Dmitriev already pointed some of them out.
The n is needed, even though #Nikolai Dmitriev said it's not. Since you want to replace it with its ASCII value. However, you can shorten it to String a = String.valueOf((int) c); or even get rid of the c and just straight up use `String a = String.valueOf((int) sb.charAt(i));
You are using sb.replace(char start, char end, String str); while the function should accept sb.replace(int start, int end, String str);. To correct this, just use sb.replace(i, i + 1, a);. Notice that you use end = i + 1 because the StringBuilder replace function end value is exclusive (not including).
Initialize result at the end. The variable has a scope of inside the for loop if you do it inside, and since you want to return it, you would want to initialized it after you finish replacing all even-indices.
I'm trying to search and reveal unknown characters in a string. Both strings are of length 12.
Example:
String s1 = "1x11222xx333";
String s2 = "111122223333"
The program should check for all unknowns in s1 represented by x|X and get the relevant chars in s2 and replace the x|X by the relevant char.
So far my code has replaced only the first x|X with the relevant char from s2 but printed duplicates for the rest of the unknowns with the char for the first x|X.
Here is my code:
String VoucherNumber = "1111x22xx333";
String VoucherRecord = "111122223333";
String testVoucher = null;
char x = 'x'|'X';
System.out.println(VoucherNumber); // including unknowns
//find x|X in the string VoucherNumber
for(int i = 0; i < VoucherNumber.length(); i++){
if (VoucherNumber.charAt(i) == x){
testVoucher = VoucherNumber.replace(VoucherNumber.charAt(i), VoucherRecord.charAt(i));
}
}
System.out.println(testVoucher); //after replacing unknowns
}
}
I am always a fan of using StringBuilders, so here's a solution using that:
private static String replaceUnknownChars(String strWithUnknownChars, String fullStr) {
StringBuilder sb = new StringBuilder(strWithUnknownChars);
while ((int index = Math.max(sb.toString().indexOf('x'), sb.toString().indexOf('X'))) != -1) {
sb.setCharAt(index, fullStr.charAt(index));
}
return sb.toString();
}
It's quite straightforward. You create a new string builder. While a x or X can still be found in the string builder (indexOf('X') != -1), get the index and setCharAt.
Your are using String.replace(char, char) the wrong way, the doc says
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
So you if you have more than one character, this will replace every one with the same value.
You need to "change" only the character at a specific spot, for this, the easiest is to use the char array that you can get with String.toCharArray, from this, this is you can use the same logic.
Of course, you can use String.indexOf to find the index of a specific character
Note : char c = 'x'|'X'; will not give you the expected result. This will do a binary operation giving a value that is not the one you want.
The OR will return 1 if one of the bit is 1.
0111 1000 (x)
0101 1000 (X)
OR
0111 1000 (x)
But the result will be an integer (every numeric operation return at minimum an integer, you can find more information about that)
You have two solution here, you either use two variable (or an array) or if you can, you use String.toLowerCase an use only char c = 'x'
So we haven't learned arrays yet in class, but we have an assignment that requires us to assign numerical values to letters. At least, we aren't told we need this, but that's the only way I can think of doing it. (Encrypting a string through shifting characters a specific way). I don't mean assign the same value for the same letter, I mean in like a "abba" string, it changes to "0123".
Thanks
Your best option then would be to use a loop. For example:
String str = "abba";
String numbers = "";
for (int i=0; i<str.length(); i++){
numbers = numbers + Integer.toString(i);
}
This way you will go through each character in str and you will create a new string of numbers with the index of each character in str. The result for numbers will be "0123" just as you requested.
I have a string and I want to use some formulas, in which there is a word that is going to be searched. Sometimes that word could be in different place, depending on the user. In order to make substrings work, I have to ensure that when it happens, the code still works.
String temp = s;//Temp is a long string text
String fehlerspeicher="fehlerspeicher";
if(temp.matches(".*"+fehlerspeicher+".*")){
// i have to find as an integer, how many LETTERS are used till this spesific word
}//to make changes in the following code
String temp1=temp.substring(0, 15000);//15000 is an example. it can be 5000 or 20000 sometimes. It splits the text up from 15000th letter.
String temp2=temp.substring(15000);// It'd be useful to use this integer in these 2 formulas.
temp2=temp2.replaceFirst("200", "20_");
temp=temp1+temp2;
So, could it be somehow implementable? Thanks.
Use indexOf:
public int indexOf(String str)
Returns the index within this string of the first occurrence of the
specified substring.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String)
So to get the index of "fehlerspeicher" you can use:
int index = temp.indexOf("fehlerspeicher");
So to get the position of the 'f' in 'fehlerspeicher' you can use:
String temp = "hellofehlerspecher"; //example temp string
int index = temp.indexOf("fehlerspeicher");
int fPos = index + 1; //fpos will equal 6.
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;