【问题标题】:Why is the variable String type, even though I converted it to int?为什么变量 String 类型,即使我将它转换为 int?
【发布时间】:2021-10-23 00:29:20
【问题描述】:

变量 int g 应该是一个 int,但是在输出时它被当作一个字符串,无法弄清楚什么是错的。

class scantest
    {
        public static int String_to_Int(String a)       
        {
            int n=Integer.parseInt(a);
            return n;
        }
        public static int brooh()
        {
            String a="43";
           int s=String_to_Int(a);
            return s;
        }
        public static void main()
        {
            int g=brooh();
            System.out.println(g +"\n" +g+1);
        }
    }

输出

43
431

【问题讨论】:

  • g +"\n" +g 是一个字符串。

标签: java bluej parseint


【解决方案1】:

System.out.println 语句内的所有算术运算(在您的情况下为 +),必须在括号内完成。

您的打印语句如下所示:

System.out.println(g +"\n" + (g+1));

注意g+1 在括号内

【讨论】:

  • 应该注意的是,这在System.out.println 内部并没有什么神奇的不同:这些是适用于任何上下文中字符串连接的一般规则。所以String s = g + "\n" + g + 1 会面临同样的问题。
  • 比这更基本。考虑运算符优先级。
  • 没问题!将此标记为已接受的答案,并确保阅读留下的其他评论,因为它提供了更多见解:)
猜你喜欢
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2016-05-20
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多