gpt4 book ai didi

java - 找不到 java.util.Scanner 的符号 hasNextInt

转载 作者:搜寻专家 更新时间:2023-11-01 03:57:13 26 4
gpt4 key购买 nike

我正在自学 Java,并且遇到了一个我想解决的问题。这是问题所在:

Write a class named Calculator with a method int sum(String s). String s contains a set of integers separated by white space (blanks, tabs, or newlines). Return the sum of the integers.

You can use a Scanner object to solve this problem. Create a new Scanner(s) and store it in a variable, say in. Then, use in.hasNextInt() to control a while loop. Each iteration of the while loop uses in.nextInt() to get the next integer from the String s. Accumulate this integer into a variable and return that variable when the loop exits.

You may use a main method to test your method by creating an instance of the Calculator class and calling sum(…) with several combinations of values using that instance.


到目前为止我的代码是

import java.util.Scanner;

public class calculator{
public int sum(String s){
new Scanner(s);
String in = s;
while (s.hasNextInt()) {
s = in.nextInt();
}
return(0);
}
}

我还没有完成类(class),但我收到一个错误提示

cannot find symbol : method hasNextInt()

为什么?我不太确定从这一点开始该做什么,所以我应该做什么? s是否正确存储到in中?

最佳答案

你的变量声明,

new Scanner(s);
String in = s;

完全错误。您必须将扫描仪存储在变量中。这意味着:

Scanner myScanner = new Scanner(s);

然后

while (myScanner.hasNextInt())

关于java - 找不到 java.util.Scanner 的符号 hasNextInt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18719959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com