【问题标题】:How to place spaces in between input textfield如何在输入文本字段之间放置空格
【发布时间】:2013-10-29 08:59:45
【问题描述】:

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

    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() 函数,有没有人有一个链接解释它,所以我也可以做这个工作?提前致谢!

【问题讨论】:

  • 将连接的String 分配给int 变量将无济于事。试试看一下相关类的JavaDoc,挺好的。也许使用教程也是一个很好的第一步。
  • 你在哪里使用cijfer?不要循环访问带有幻数的元素。
  • 知道了!感谢大家的cmets,他们帮助了:)
  • 你还是应该接受答案...

标签: java charat


【解决方案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 文档

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.

【讨论】:

    【解决方案2】:

    用直接的话你不能。您不能在 int 数据类型中添加空格,因为 int 仅用于存储整数值。将int 更改为String 以存储两者之间的空间。

    【讨论】:

      【解决方案3】:

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

      1. 您的 for 循环是基于 1 的,而不是标准的基于 0 的循环。这一点都不好。
      2. 您尝试将 char 分配给 String(3 次),第一次调用 charAt 是正确的,但由于某种原因,您随后切换到使用 String?
      3. 最后,您尝试将 String 分配给 int,这完全是荒谬的。

      【讨论】:

        【解决方案4】:

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

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

        记住这些要点,请重试,如果需要,请寻求进一步的帮助。

        【讨论】:

          【解决方案5】:

          试试下面的代码

          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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-11-28
            • 1970-01-01
            • 2013-06-20
            • 1970-01-01
            • 1970-01-01
            • 2022-10-12
            • 1970-01-01
            相关资源
            最近更新 更多