[英]How to place spaces in between input textfield
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? 我想我还不了解charAt()
函数,没有人有一个以某种方式解释它的链接,以便我也可以进行这项工作吗? Thanks in advance! 提前致谢!
In straight words You can't. 直截了当地说你不能。 You can't add space in int
datatype because int
is meant to store the integer value only. 您不能在int
数据类型中添加空间,因为int
仅用于存储整数值。 Change int
to String
to store the space in between. 将int
更改为String
以存储它们之间的空间。
Okay, let's see what's wrong with your code... 好的,让我们看看您的代码有什么问题...
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 来自Java文档的更多详细信息
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.
You have a number of problems, but well done on an honest attempt. 您有许多问题,但是经过诚实的尝试,做得很好。
charAt(0)
gives you the first character, charAt(1)
gives you the second character, and so on. 首先,字符串中的索引从零开始,因此charAt(0)
给您第一个字符, charAt(1)
给您第二个字符,依此类推。 charAt
three times is probably unnecessary. 其次,可能不需要重复三遍对charAt
所有调用。 charAt
is a char
, not a String
, so you can't assign it to a String
variable. charAt
的返回值是char
,而不是String
,因此您不能将其分配给String
变量。 Likewise, on the last line, don't assign a String
to an int
variable. 同样,在最后一行,不要将String
分配给int
变量。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.