gpt4 book ai didi

java - 扫描仪提示用户输入数字

转载 作者:行者123 更新时间:2023-12-01 13:19:48 26 4
gpt4 key购买 nike

以下是我尝试遵循的说明:

Write a method called negative sum that accepts a scanner reading input from a file containing a series of integers., and a print message to the console indicating whether the sum starting from the first number is ever negative.You should alse return true if a negative sum can be reached and false if not. for example, suppose the file contains the 38 4 19 -27 -15 -3 4 19 38 your method would consider the sum of just number (38) , the first two numbers ( 38 + 4) the firs three number ( 38 + 4 + 19) and so on to the asnd . none of thes sume is negative so the method would produce the following output and return false : No negative numbers.

If the file instead contains 14 7 -10 9 -18 -10 17 42 98 the method finds that a negative sum of -8 is reached after adding the first six numbers. it should output the following to the console and return true: sum of -8 after 6 steps.

这就是我到目前为止所拥有的。我只是在添加扫描仪以提示用户输入数字时遇到问题。

import java.io.*;
import java.util.*;

public class NegativeSum{
public static void main (String [] args )
throws FileNotFoundException{


negativesum();


}//end of amin

public static boolean negativesum()
throws FileNotFoundException{


File file = new File ("negativeSum.txt");
Scanner input = new Scanner (file);

int sum=0;
int count = 0;

while ( input.hasNextInt()){
int next =input.nextInt();
sum+=next;
count++;

if ( sum<0){
System.out.println("sum of " + sum + " after " + count + "steps" );
return true;
}

}///end of while
System.out.println("no negative sum ");
return false;




}//end of metho d

}//end of main

最佳答案

我在您的实现中看到的唯一严重错误(相对于您的问题陈述)是您的方法应该接收 Scanner 作为输入(例如接受扫描仪) -

public static boolean negativeSum(Scanner input) {
if (input == null) {
// Handle null - e.g. no value
return false;
}
int sum = 0;
int count = 0;

while (input.hasNextInt()) {
int next = input.nextInt();
sum += next;
count++;

if (sum < 0) {
System.out.println("sum of " + sum + " after "
+ count + " steps");
return true;
}
}// /end of while
System.out.println("no negative sum");
return false;
}

关于java - 扫描仪提示用户输入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138458/

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