【问题标题】:Is there a way to pass a 16 digit integer? and if so, how can it be done?有没有办法传递一个 16 位整数?如果是这样,怎么办?
【发布时间】:2023-03-06 01:57:01
【问题描述】:

我需要让用户输入一个十六位数字(不带后缀或引号),然后将该数字传递给一个对象。每当我尝试输入这样的数字时,它都会被视为“数据类型 int 超出范围”。我不希望用户必须将其输入为 XXXXXXXXXXXXXXXXL,因为用户可能不知道 java 需要一个 L 来表示 longs。我也不希望它在数字周围加上引号。有没有办法在 java 抛出有关数据类型不匹配或超出范围异常的异常之前进行转换?

这甚至可以做到吗?我正在尝试构建一个Customer 对象,它是Order 对象中的一个字段,该对象本身位于ArrayList<Order> orderList 中。 "Sam Totman" 及其旁边的数字是我正在使用的参数示例。

    orderList.get(1).setBuyer(new Customer("Sam Totman", 2112112121121121));

我在这个构造函数中放置 datatype 的地方应该去哪里? ccn 是信用卡号;

    public class Customer
    {
        private String name;
        private *datatype* ccn;

        Customer(String name, *datatype* ccn)
        {
            this.name = name;
            this.ccn = ccn;
        }

【问题讨论】:

  • 您将数字文字(已编码到您的程序中)与内部表示混淆了。
  • 让我们假设输入是一个 Scanner(System.in)。如何才能做到这一点? BigInteger 数据类型会起作用吗?
  • 如何将String 传递给long?或者如何从Scanner 获得long
  • @ReiHinoX 使用 Long.parseLong 时,您的用户不必在数字输入的末尾输入 L 即可将其解析为 long
  • 您不会对这个 16 位数的值进行任何算术运算,因此将其作为任何类型的整数都是没有意义的。只需将其读取为字符串即可。

标签: java object types constructor largenumber


【解决方案1】:

使用扫描器处理输入

    Scanner scan = new Scanner(System.in);      
    long aLong = scan.nextLong(10); 
    ....       
    orderList.get(1).setBuyer(new Customer("Sam Totman", aLong));

客户

public class Customer
{
    private String name;
    private long ccn;

    Customer(String name, long ccn)
    {
        this.name = name;
        this.ccn = ccn;
    }
}

【讨论】:

    【解决方案2】:
    orderList.get(1).setBuyer(new Customer("Sam Totman", new Scanner(System.in).nextLong());
    

    【讨论】:

    • 请您详细说明您的代码,并说明它如何解决问题。这将在未来对其他人有所帮助
    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多