【问题标题】:Read number as string sequence and convert first and last to an Integer将数字读取为字符串序列并将 first 和 last 转换为 Integer
【发布时间】:2019-03-17 05:02:46
【问题描述】:

我是编程新手,刚开始学习 Java。
我想做一个程序是

  • 要求用户输入一个包含数字序列的字符串,然后
  • 获取该序列的第一个和最后一个数字,并
  • 检查这些数字是奇数还是偶数

根据这些信息,它会做某些事情。

这是我的代码:

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String n = kb.nextLine();
    Integer x = Integer.valueOf(n.charAt(n.length() - 1));
    Integer y = Integer.valueOf(n.charAt(0));
    String out;
    if (y % 2 == 0 && x % 2 == 0) {
        out = "$" + n.substring(1, n.length() - 1) + "$";
    } else if (y % 2 > 0 && x % 2 > 0) {
        out = "X" + n.substring(1, n.length() - 1) + "X";
    } else if (x == 0); {
        out = n.substring(0, n.length() - 1) + "#";
    }
    System.out.println(out);
}

我不确定是什么问题。我认为是关于这两行

Integer x = Integer.valueOf(n.charAt(n.length()-1));
Integer y = Integer.valueOf(n.charAt(0));

输出值与输入值不同..

【问题讨论】:

  • 这个答案对您有帮助吗?
  • 绝对的,非常感谢你!虽然很抱歉回复晚了..

标签: java string char numeric value-of


【解决方案1】:

扫描仪代码可以改进,您的转换确实存在问题。您的代码获取这些符号的 ASCII 值。试试这样:

public static void main (String[] args) throws java.lang.Exception
{
    Scanner console = new Scanner(System.in);

    while (console.hasNextLine()) {
        String n = console.nextLine();
        Integer x = Integer.parseInt(n.substring(n.length()-1));
        //System.out.println(x);
        Integer y = Integer.parseInt(n.substring(0, 1));
        //System.out.println(y);
        String out;
        if (y % 2 == 0 && x % 2 == 0)
        {
            out = "$"+n.substring(1, n.length()-1)+"$";
        }
        else if (y % 2 > 0 && x % 2 > 0) {
            out = "X" +n.substring(1, n.length()-1) + "X";
        }
        else if (x == 0); 
        {
        out = n.substring(0, n.length()-1)+ "#";
        }
        System.out.println(out);
    }
}

Online Demo

我使用过 substring()/parseInt(),但是有很多方法可以将 stringchar 转换为 Integer。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-07
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2017-04-13
    • 1970-01-01
    相关资源
    最近更新 更多