如何输入多个数据单元并在 Java 中使用计数器

How do I input multiple units of data and utilize a counter in Java

大家好,我正在尝试获取它,以便我的程序能够获取多个用户的数据,然后在 while 循环完成后打印所有这些数据(我将计数器设置为 1,所以一个新的一组信息可以在最后一个之后输入,但如果达到两个人的限制,它将停止并打印信息)。我已经能够使用用户输入数据获得正确打印的信息,但是我无法让多个人输入数据,而且即使我能够打印也无法打印出一组以上的数据接收不止一个用户的数据。我将如何做这两件事?这是我到目前为止的代码:

public class credLimit {
public static void main(String[]args){
    Scanner input = new Scanner(System.in);

    int newBalance = 0;
    int credCounter = 1;


    while(credCounter <= 2){
        System.out.print("Enter account number: ");
        int accNum = input.nextInt();
        System.out.print("Enter your beginning balance: ");
        int beginningBalance = input.nextInt();
        System.out.print("Enter your total charges this month: ");
        int charges = input.nextInt();
        System.out.print("Enter your total credit applied this month: ");
        int credit = input.nextInt();
        System.out.print("Enter your allowed credit limit: ");
        int maxcredLimit = input.nextInt();
        newBalance = beginningBalance + charges - credit;
        credCounter = credCounter + 1;

        System.out.printf("%nAccount number: %d%n", accNum);
        System.out.printf("Your new balance: %d%n", newBalance);
        if(newBalance <= maxcredLimit)
            System.out.printf("You have not exceeded your credit limit. %d%n");
        else if (newBalance > maxcredLimit)
            System.out.printf("Credit limit exceeded. %d%n");
    }
}

之前可以取多组信息,现在只能取其中一组用户数据,计算(判断是否超过信用额度),打印出来。出于某种原因,它一直停在一个用户的信息上,而不是让两个用户输入他们的信息,这是为什么?

我猜你的代码崩溃了,因为你没有向最后 2 个打印语句传递任何参数:

if(newBalance <= maxcredLimit)
    System.out.printf("You have not exceeded your credit limit. %d%n");
else if (newBalance > maxcredLimit)
    System.out.printf("Credit limit exceeded. %d%n");

您的意思是:

if(newBalance <= maxcredLimit)
    System.out.printf("You have not exceeded your credit limit. %d%n", newBalance);
else if (newBalance > maxcredLimit)
    System.out.printf("Credit limit exceeded. %d%n", newBalance);