如何在java中使用for循环减去n个数字?

时间:2014-09-11 03:12:11

标签: java for-loop exception-handling subtraction

当我使用for循环进行减法时,我没有得到正确的输出。

我应该在我的代码中使用什么逻辑来正确地使用for循环来减少我的减法?

请帮助我,因为我是JAVA的新手。

我的代码如下:

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

class Sub
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        int a,n,i;
        String yn;
        boolean loop=true;

        while(loop)
        {
            try
            {
                do
                {
                    loop=true;
                    System.out.println("Enter how many numbers to Subtract?: ");
                    n=s.nextInt();
                    int sum=0;
                    for(i=1;i<=n;)
                    {
                        try
                        {
                            System.out.println("Enter number "+i+" : ");
                            a=s.nextInt();
                            sum=a-sum;
                            i++;
                        }
                        catch(Exception e)
                        {
                            System.out.println("Invalid Entry. Try again!!");
                        }
                    }
                    System.out.println("Answer is:"+sum);
                    System.out.println("Do you want to continue?(Y/N): ");
                    yn=s.next();
                    loop=yn.equals("Y")||yn.equals("y");
                }while(loop);
            }
            catch(Exception e)
            {
                System.out.println("Re-enter the Limit");
            }
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您应该从sum开始作为第一个数字(不是零)并从中减去其余数字:

    loop=true;
    System.out.println("Enter how many numbers to Subtract?");
    n=s.nextInt();
    int sum=0;
    for(i=1;i<=n;)
    {
        try
        {
            System.out.println("Enter number "+i+" : ");
            a=s.nextInt();
            sum=a-sum;
            i++;
        }
        catch(Exception e)
        {
            System.out.println("Invalid Entry. Try again!!");
        }
    }

为:

...
loop = true;
System.out.println("Enter how many numbers to Subtract?: ");
n = s.nextInt();
System.out.println("Enter number 1 : ");
int sum = s.nextInt();
for (int i=2; i <= n; i++) {
    try {
        System.out.println("Enter number " + i + " : ");
        a = s.nextInt();
        sum -= a;
    } catch (Exception e) {
        System.out.println("Invalid Entry. Try again!!");
    }
}
...

此外,而不是:

yn.equals("Y") || yn.equals("y")

您可以使用equalsIgnoreCase()

yn.equalsIgnoreCase("Y")

最后,你应该为变量使用有意义的名称(即使它是如此小的程序,也建议它养成良好的习惯),而不是:

    int a, n, i; // you can define and use i inside the for-loop - no need to define it outside
    String yn;

考虑使用更具表现力的名称,例如:

    int inputNumber, numberOfVariables;
    String continueLooping;

可以改进以下版本(进一步重构):

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        int numOfArguments = getNumberOfArguments(scanner);
        int sum = getNextNumberFromUser(scanner, 1);
        for (int i = 2; i <= numOfArguments; i++) {
            sum -= getNextNumberFromUser(scanner, i);
        }
        System.out.println("Answer is: " + sum + "\n\nDo you want to continue?(Y/N): ");
        String runAgain = scanner.next();
        if (runAgain.equalsIgnoreCase("N")) {
            break;
        }
    }
}

private static int getNextNumberFromUser(Scanner scanner, int i) {
    while (true) {
        try {
            System.out.println("Enter number " + i + " : ");
            return scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Invalid Entry. Try again!!");
            scanner.nextLine();
        }
    }
}

private static int getNumberOfArguments(Scanner scanner) {
    int numberOfArguments = -1;
    System.out.println("Enter how many numbers to Subtract?: ");
    while (numberOfArguments == -1) {
        try {
            numberOfArguments = scanner.nextInt();
            if (numberOfArguments <= 0) {
                numberOfArguments = -1;
            }
        } catch (InputMismatchException e) {
            System.out.println("Illegal number of arguments to subtract, please try again: ");
            scanner.nextLine();
        }
    }
    return numberOfArguments;
}