简体   繁体   English

如何使用扫描仪从同一行读取多个浮点数?

[英]How do I read multiple floats from the same line with a scanner?

I'm a new programmer, and for an assignment I have to write a program that asks the user to enter three numbers, and returns the smallest to them.我是一名新程序员,为了完成一项任务,我必须编写一个程序,要求用户输入三个数字,并返回最小的数字。 I don't know how to make each entry it's own float.我不知道如何让每个条目都有自己的浮动。 So far, I have:到目前为止,我有:

static float smallest(float a, float b, float c);

System.out.println("Enter three numbers");

I don't know how to clarify that the next line holds the floats for a, b, and c. We also just learned what "static float smallest" means, and I'm still very confused, so I'm sorry if the answer is obvious.我不知道如何澄清下一行包含 a、b 和 c 的浮点数。我们也刚刚了解了“最小静态浮点数”的含义,我仍然很困惑,如果答案很明显。

import java.util.Scanner;

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);

    System.out.println("Enter three numbers");

    float a = myObj.nextFloat();
    float b = myObj.nextFloat();
    float c = myObj.nextFloat();

    System.out.println("Smallest numb: " + smallest(a, b, c));

  }
}

Change println to print将 printl 更改为打印

System.out.print("Enter three numbers: ");

and

use useDelimiter(pattern) in java.util.Scanner在 java.util.Scanner 中使用useDelimiter(pattern)

Scanner myObj = new Scanner(System.in).useDelimiter("\\s* \\s*");

From the javadoc for class Scanner :来自 class Scannerjavadoc

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.扫描仪使用分隔符模式将其输入分解为标记,默认情况下匹配空格。

This means you can enter three float numbers separated by a space on one line and read all three with a Scanner .这意味着您可以在一行中输入三个由空格分隔的float ,然后使用Scanner读取所有三个。

Apparently you want your program to accept these three numbers from the user.显然您希望您的程序接受来自用户的这三个数字。 Hence you can create a Scanner that wraps the standard input, ie System.in .因此,您可以创建一个包装标准输入的Scanner ,即System.in Example code follows:示例代码如下:

float a;
float b;
float c;
Scanner stdin = new Scanner(System.in);
System.out.print("Enter three numbers: ");
if (stdin.hasNextFloat()) {
    a = stdin.nextFloat();
}
if (stdin.hasNextFloat()) {
    b = stdin.nextFloat();
}
if (stdin.hasNextFloat()) {
    c = stdin.nextFloat();
}

Note that the above code only accepts three float numbers but does not determine which of them is the smallest - since you only asked how to accept three float numbers.请注意,上面的代码仅接受三个float ,但无法确定其中最小的 - 因为您只询问了如何接受三个float

Here is an example of running the above code:以下是运行上述代码的示例:

Enter three numbers: 1.1 2.2 3.55

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM