簡體   English   中英

掃描儀提示用戶輸入數字

[英]Scanner to prompt user for numbers

以下是我要遵循的說明:

編寫一個稱為負數總和的方法,該方法接受掃描儀從包含一系列整數的文件中讀取輸入,並向控制台顯示一條打印消息,指示從第一個數字開始的總和是否為負數。如果為負數,還應返回true可以達到總和,否則不可以。 例如,假設文件包含38 4 19 -27 -15 -3 4 19 38您的方法將考慮正數(38),前兩個數字(38 + 4)和第三個數字(38 + 4 + 19),以此類推。 它們的sume都不為負,因此該方法將產生以下輸出並返回false:沒有負數。

如果該文件包含14 7 -10 9 -18 -10 17 42 98,則該方法發現在加上前六個數字后達到負-8。 它應將以下內容輸出到控制台並返回true:6個步驟后的總和為-8。

到目前為止,這就是我所擁有的。 我只是在添加掃描儀以提示用戶輸入數字時遇到麻煩。

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;
}

我在問題描述中沒有看到任何要求您提示用戶輸入數字的內容。 您的代碼似乎已經滿足指定的分配要求。

但是,如果您確實想這樣做:

  • System.in是一個InputStream代表標准輸入。
  • Scanner(InputStream)構造函數創建一個Scanner ,該Scanner從指定的InputStream讀取。

我將把它留給您作為練習,以弄清楚如何將兩者結合在一起。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM