如何保持 scnr.hasNext() 为 true。

huangapple 未分类评论43阅读模式
英文:

How to keep scnr.hasNext() true

问题

我正在调试代码的一部分,我意识到它不按照我的预期工作。我想输入一些数字,让 int var 逐个存储它们,如果有更多的数字输入,保持 scnr.hasNext() 为 true,以便我的 while 循环继续运行,并且我可以对每个数字执行操作。

public static Number evaluateExpression(String expr) {
    Scanner scnr = new Scanner(expr);
    int var = 0;
    while (scnr.hasNext()) {
        System.out.println(scnr.hasNext());
        var = scnr.nextInt();
        System.out.println(scnr.hasNext());
    }
}

目前,如果我输入 5、4,输出为 true false false,所以 var = scnr.nextInt(); 使得 (scnr.hasNext()); 变为 false。我该如何修复这个问题?我还需要一种方法来存储下一个 scnr 值,如果它是一个字符串,那么

String input = "";
input = scnr.next();

会在有更多输入时保持 scnr.hasNext() 为 true。

英文:

I am debugging a part of my code that I have realized isn't working how I want it. I want to enter a couple numbers and have int var store them one by one, and keep scnr.hasNext() true if there were more numbers inputted, so that my while loop continues and I can run operations on every number.

public static Number evaluateExpression(String expr) {
Scanner scnr = new Scanner(expr);    
int var = 0;
while (scnr.hasNext()) {
    System.out.println(scnr.hasNext());
    var = scnr.nextInt();
    System.out.println(scnr.hasNext());
}

Currently if I give it input of 5, 4, the output is true false false, so var = scnr.nextInt(); is making (scnr.hasNext()); false. How do I fix that? I also need a way to store the next scnr value if it is a string too, so

String input = "";
input = scnr.next();

would keep scnr.hasNext() true if there is more input given.

huangapple
  • 本文由 发表于 2020年4月4日 11:21:10
  • 转载请务必保留本文链接:https://java.coder-hub.com/61023362.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定