【问题标题】:Incrementing "whitespace" for "5" times will cause an error?将“空白”增加“5”次会导致错误吗?
【发布时间】:2015-10-24 19:02:40
【问题描述】:

有一个分配,其中我必须将字符串中的每个索引增加用户设置的数量以生成新名称。

换句话说:

输入你的名字: 海伦李 键入要递增的整数: 1 新名称:gfmfo!mff

因此,使“helen lee”中的每个索引都增加 1。

这就是问题所在。 Java 将字符串中的每个索引视为一个字符。甚至空格。 因此,当我将“*whitespace”增加 2 时,它将产生“@”。

但是

当我将空格增加 5 时,会发生错误。 (应该产生“%”)。 有没有其他方法可以在不调用错误的情况下将空格增加 5?

这是我的代码:

    String alpha = " ";
    int integer = 0;

    System.out.println("Question 1: ");
    Scanner alphaInput = new Scanner(System.in); 
    System.out.println("Please enter your name. "); 
    alpha = alphaInput.nextLine();

    Scanner intInput = new Scanner(System.in);
    System.out.println("How many cycles to cycle your name: ");
    integer = intInput.nextInt();

    int stringIndex = alpha.length();
    char newName; 

    System.out.printf("Your new name is: "); 
    for(int i = 0; i < stringIndex; i++)
    {
        newName = (char) (alpha.charAt(i) + integer); 
        System.out.printf("" + newName);
    };

【问题讨论】:

  • 旁注:您不需要在每次请求输入时都实例化新的Scanners。只需重新使用旧的

标签: java string char whitespace increment


【解决方案1】:

问题是你使用System.out.printf。该方法将% 解释为特殊值,并期望更多数据。您应该改用 System.out.print(不带 f)。有关更多详细信息,请参阅 documentationprintf

【讨论】:

  • 哇,谢谢!有效!不知道 printf 和 print 之间有什么区别。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 2022-12-18
  • 2014-04-06
相关资源
最近更新 更多