簡體   English   中英

Java 求和一個整數

[英]Java Sum an integer

我想從用戶那里讀取一個數字,然后對輸入的數字的最后七位數字求和。 做這個的最好方式是什么? 這是我的代碼,但不幸的是它不起作用:

class ersteAufgabe {
  public static void main (String[] args)
  {
              Scanner s = new Scanner(System.in);
              double [] a = new double[10];
              for (int i = 0;i<10;i++)
              {
                  a[i]=s.nextInt();

                 }
              s.close();
              System.out.println(a[0]);
  }
}

我只想讀取一個數字並將其用作數組。 直到現在他才期望我提供 10 個輸入。

首先,您必須識別輸入的值是否為數字且至少有 7 位數字。 除非你必須輸出錯誤信息。 將輸入的值轉換為字符串並使用類 Character.isDigit(); 檢查字符是否為數字。 然后你可以使用 String 類中的一些方法,比如 substring(..)。 最后使用錯誤/有效值進行單元測試,以查看您的代碼是否健壯。 完成后使用 finally { br.close() } 關閉 BufferedReader 和 Resources。 將您的代碼推送到方法中並使用實例類 erste-Aufgabe(第一次練習)。當您真正完成時,將 JFrame 用於 GUI 應用程序。

private static final int SUM_LAST_DIGITS = 7;

public void minimalSolution() {
    String enteredValue = "";
    showInfoMessage("Please enter your number with at least " + SUM_LAST_DIGITS + " digits!");
    try (Scanner scan = new Scanner(System.in)) {
        enteredValue = scan.next();
        if (enteredValue.matches("^[0-9]{" + SUM_LAST_DIGITS + ",}$")) {
            showInfoMessage(enteredValue, lastDigitsSum(enteredValue));
        } else {
            showErrorMessage(enteredValue);
        }
    } catch(Exception e) {
        showErrorMessage(e.toString());
    }
}

public int lastDigitsSum(String value) {
    int count = 0;
    for (int i = value.length() - 1, j = 0; i >= 0 && j < SUM_LAST_DIGITS; i--, j++)
        count += value.charAt(i) - '0';
    return count;
}

public void showInfoMessage(String parMessage) {
    System.out.println(parMessage);
}

public void showInfoMessage(String parValue, int parSum) {
    System.out.println("Your entered value: [" + parValue + "]");
    System.out.println("The summed value of the last 7 digits are: [" + parSum + "]");
}

public void showErrorMessage(String parValue) {
    System.err.println("Your entered value: [" + parValue + "] is not a valid number!");
}
public static int lastDigitsSum(int total) {
    try (Scanner scan = new Scanner(System.in)) {
        String str = scan.next();
        int count = 0;

        for (int i = str.length() - 1, j = 0; i >= 0 && j < total; i--, j++) {
            if (Character.isDigit(str.charAt(i)))
                count += str.charAt(i) - '0';
            else
                throw new RuntimeException("Input is not a number: " + str);
        }

        return count;
    }
}

暫無
暫無

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

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