【问题标题】:How do i declare and read values into integer values?我如何声明并将值读入整数值?
【发布时间】:2014-12-21 07:41:18
【问题描述】:

我真的是 Java 新手,我正在上计算机科学的入门课程。我需要知道如何提示用户输入两个值,声明和定义 2 个变量来存储整数,然后能够读取这些值,最后将这些值打印出来。但我很迷茫,我什至不知道如何开始我花了一整天的时间尝试.. 我真的需要一些帮助/指导。我需要对整数、十进制数和字符串这样做。有人可以帮我吗?

【问题讨论】:

  • 他们不是在课堂上教你怎么做吗?
  • 我错过了第二天的讲座......我看了我们的在线课程,但我看到的只是即将到来的测试:(
  • reading int from console的可能重复

标签: java


【解决方案1】:

您可以通过使用 Scanner 类来做到这一点: 一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串。 Scanner 使用分隔符模式将其输入分解为标记,默认情况下匹配空格。然后可以使用各种 next 方法将生成的标记转换为不同类型的值。

例如,此代码允许用户从 System.in 中读取一个数字:

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);

nextInt() : - 将输入的下一个标记扫描为 int 并返回从输入扫描的 int。

对于more

或者要获取用户输入,您还可以使用 Console 类:提供访问与当前 Java 虚拟机关联的基于字符的控制台设备(如果有)的方法。

Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

或者你也可以使用 BufferedReaderInputStreamReader 类和 DataInputStream 类来获取用户输入。

【讨论】:

    【解决方案2】:

    使用Scanner 类从用户那里获取值。对于整数,您应该使用int,对于十进制数(也称为实数)使用double,对于字符串使用Strings

    一个小例子:

    Scanner scan = new Scanner(System.in);
    int intValue;
    double decimalValue;
    String textValue;
    
    System.out.println("Please enter an integer value");
    intValue = scan.nextInt(); // see how I use nextInt() for integers
    System.out.println("Please enter a real number");
    decimalValue = scan.nextDouble(); // nextDouble() for real numbers
    System.out.println("Please enter a string value");
    textValue = scan.next();    // next() for string variables
    
    System.out.println("Your integer is: " + intValue + ", your real number is: "
                                    + decimalValue + " and your string is: " + textValue);
    

    如果你还是不明白,请通过谷歌进一步查看Scanner类。

    【讨论】:

      【解决方案3】:

      因为你可能会在你的课堂和你的编程生涯中继续遇到这样的问题:

      钓鱼课。

      现在到鱼了。

      您可以使用Scanner 类。文档中提供的示例。

      Scanner sc = new Scanner(System.in);
      int i = sc.nextInt();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 2019-11-16
        • 2021-10-26
        • 1970-01-01
        • 2017-08-04
        • 1970-01-01
        相关资源
        最近更新 更多