如何在输入文本字段之间放置空格

时间:2013-10-29 08:59:45

标签: java charat

我正在尝试在文本字段中输入的数字之间放置空格。我使用以下代码:

    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;

我想我还不了解charAt()功能,有没有人用某种方式解释它,所以我也可以做这个工作呢?提前谢谢!

5 个答案:

答案 0 :(得分:1)

直言不讳。您无法在int数据类型中添加空格,因为int仅用于存储整数值。将int更改为String以将空格存储在其间。

答案 1 :(得分:1)

好的,让我们看看您的代码有什么问题......

  1. 您的for循环是基于1的,而不是基于标准的0。这根本不好。
  2. 您正在尝试将字符串赋值给String(3次),对charAt的第一次调用是正确的,但由于某种原因您转而使用字符串?
  3. 最后你试图将一个String分配给一个int,这完全没有意义。

答案 2 :(得分:1)

实施例

public class Test {

   public static void main(String args[]) {
      String s = "Strings are immutable";
      char result = s.charAt(8);
      System.out.println(result);
   }
}

这会产生以下结果:

a

更多细节来自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.

答案 3 :(得分:0)

你有很多问题,但在诚实的尝试中做得很好。

  • 首先,字符串中的索引从零开始,因此charAt(0)为您提供第一个字符,charAt(1)为您提供第二个字符,依此类推。
  • 其次,重复拨打charAt三次电话可能是不必要的。
  • 第三,你必须小心你的类型。 charAt的返回值为char,而不是String,因此您无法将其分配给String变量。同样,在最后一行,请勿将String分配给int变量。
  • 最后,如果文字字段中没有足够的字符,我认为您并未考虑会发生什么。

请注意这些要点,请再试一次,如果需要,请寻求进一步的帮助。

答案 4 :(得分:0)

尝试以下代码

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