【问题标题】:Sum of digits using Java [closed]使用Java的数字总和[关闭]
【发布时间】:2021-05-18 18:06:44
【问题描述】:

我是编程初学者,我正在尝试使用 Java 输出用户输入的数字总和。

代码应该根据数字的长度说出特定的消息,并在用户键入空格时结束。

我的代码正确执行。但是,它仅适用于第一个输入。第一次输入后,我收到一条错误消息。

我怎样才能修复我的代码,以便我的 while 循环有效地工作?

    //scanner
    Scanner input = new Scanner (System.in);

    //ask user for a credit card number
    System.out.print("Enter a credit card number (enter a blank line to quit): ");
    String userNum = input.nextLine();
    
    
    //length and last char of string
    int len = userNum.length();
    char lastDigit = userNum.charAt(len-1);
    
    
    //initial values
    int sumOfDigits = 0;
    int strNum = 0;
    int i;

    //loops
    while (len > 0) {
        if (len == 16) { //when length equals 16
            for (i = 0; i < 15; ++i ) { //calculates sum of digits
                String s = userNum.substring(i, i+1);
                strNum = Integer.parseInt(s);
                sumOfDigits = sumOfDigits + strNum;
            }
            System.out.println("DEBUG: Sum is " + sumOfDigits);
            System.out.println("Check digit is: " + lastDigit);
            System.out.println();    
            System.out.print("Enter a credit card number (enter a blank line to quit): ");
            userNum = input.next();
        }
        else if (userNum.equals("")) { //when user types blank space
            System.out.println("Goodbye!");
        }
        else { //when user digit is not 16, nor types a blank space
            System.out.println("ERROR! Number MUST have exactly 16 digits."); 
            System.out.println();
            System.out.print("Enter a credit card number (enter a blank line to quit): ");
                userNum = input.next();
        }
    }
    
    
    
    //input close
    input.close();

}

【问题讨论】:

  • “让我的 while 循环有效地工作”如果您的代码不起作用,请在关注效率之前处理它。
  • 在我的计算机上,您的代码适用于多个依次输入的信用变量编号。您看到了哪个错误消息?我看到的唯一问题是你的程序没有说再见和终止。
  • 读取新值后需要重新计算lenlastDigit
  • 为了在此处更好地接收您的问题(更少的反对票,更多更好的答案),请始终清楚准确地说明您的程序的预期结果以及观察到的结果有何不同。将您遇到的任何错误消息粘贴到问题中。

标签: java loops for-loop if-statement while-loop


【解决方案1】:

我可以看到的主要问题是您没有从新输入的字符串中重新计算内容。我猜具体的问题是 len 没有重新计算,这意味着您将在每次循环迭代的条件语句中输入相同的分支。

将所有从输入读取的内容放在一个地方,并将所有可以移动的变量移入循环:

while (true) {
  System.out.print("Enter a credit card number (enter a blank line to quit): ");
  // Read it.
  String userNum = input.nextLine();

  if (userNum.equals("")) {
    System.out.println("Goodbye!");
    break;
  }

  if (len == 16) {

    // Derive the values you want from it.
    //length and last char of string
    int len = userNum.length();
    char lastDigit = userNum.charAt(len-1);

    // ..
  } else {
    // Print an error... but allow the loop to execute again.
  }
}

这样,您不必担心忘记重新初始化变量,或者确保打印的消息与输入另一个值相同,并且您没有从输入中读取的不同方式(您的代码包含例如input.nextinput.nextLine)。

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多