java - java中从用户输入中解析整数?

标签 java parsing

我想从用户那里获取一个有理数,例如 188/4 的形式 最终得到 int 188 和 int 4。 在java中执行此操作的有效方法是什么? stringTokenizer 是最好的方法吗?或者c中有类似scanf的东西吗?

private int NUM;
private int DEN;
static Scanner s;
public Rational(){
    s = new Scanner(System.in).useDelimiter("/");
    System.out.println("Enter Rational number in the form of a/b:");
    NUM = s.nextInt();
    int d = s.nextInt();
    if(d == 0){
        throw new IllegalArgumentException();
    }
    else{
        DEN = d;
    }
}

当我运行此程序时,我的程序在输入数字后卡住

最佳答案

小调整...

private int NUM;
private int DEN;
static Scanner s;
public Rational(){
    System.out.println("Enter Rational number in the form of a/b:");
    s = new Scanner(System.in);
    String[] values = s.next().split("/");

    NUM = Integer.parseInt(values[0]);
    int d = Integer.parseInt(values[1]);
    if(d == 0){
        throw new IllegalArgumentException();
    } else{
        DEN = d;
    }
}

关于java - java中从用户输入中解析整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490678/

相关文章:

python - 如何在 python lark 解析器中平衡规则和终端?

java - 我想在单个 TextView 上显示 3 个 EditText 值

java - JSONArray 中未命名的 JSONArray

Python解析csv文件——用冒号代替逗号

javascript - 在函数之外使用 Angular var

c# - 如何使用 textfieldParser 编辑 CSV 文件?

java.sql.SQLSyntaxErrorException : ORA-00911: invalid character

Java 数据库连接分为 2 个类

java - Hadoop Map Reduce For Google web graph

java - 使用数据库 mysql 桌面部署 Java 应用程序