从字符串中获取扫描仪输入,而不是从System.in

时间:2017-10-25 17:21:37

标签: java

编辑无意故意分享

2 个答案:

答案 0 :(得分:0)

您可以使用'space'作为分隔符拆分字符串,然后将每个单词转换为数字

for (String str : input.split(" ")) {
    Douibe currentNum = Double.parseDouble(str);
}

答案 1 :(得分:0)

更正后的代码:(这与您提出的方式相同)

import java.util.Scanner;
import javax.swing.JOptionPane;

public class minMaxNum {

    String input = JOptionPane.showInputDialog("Enter numbers sperated by spaces:");
    Scanner numbers = new Scanner(input);

    double minNum;
    double maxNum;

    if (numbers.hasNextDouble()) {
        minNum = numbers.nextDouble();
        maxNum = minNum;

        while (numbers.hasNextDouble()) {
            double currentNum = numbers.nextDouble();
            if (currentNum < minNum) {
                minNum = currentNum;
            } else if (currentNum > maxNum) {
                maxNum = currentNum;
            }
        }
        System.out.println("Range: " + (int)minNum + " => " + (int)maxNum);
    }
}