使用私有静态

时间:2017-05-15 09:07:07

标签: java static private

你能找到错误的来源吗?

enter image description here

package calc;

import java.util.Scanner;

public class Calc {



    Scanner scan = new Scanner(System.in);

    public void add() {
        System.out.println("Enter 1st number");
        int s1 = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter 2nd number");
        int s2 = scan.nextInt();
        scan.nextLine();

        int sum = s1 + s2;
        System.out.println("The sum is: " + sum);

    }

    public void diff() {
        System.out.println("Enter 1st number");
        int d1 = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter 2nd number");
        int d2 = scan.nextInt();
        scan.nextLine();

        int diff = d1 - d2;
        System.out.println("The difference is: " + diff);

    }

    public void prod() {
        System.out.println("Enter 1st number");
        int p1 = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter 2nd number");
        int p2 = scan.nextInt();
        scan.nextLine();

        int prod = p1 + p2;
        System.out.println("The product is: " + prod);
    }

    public void quo() {
        System.out.println("Enter 1st number");
        int q1 = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter 2nd number");
        int q2 = scan.nextInt();
        scan.nextLine();

        int quo = q1 + q2;
        System.out.println("The quotient is: " + quo);
    }

    public static void main(String[] args) {
        do {

            Calc op = new Calc();
            Scanner scan = new Scanner(System.in);
            char ans = 0;

            System.out.println("Calculator");
            System.out.println("1.Addition\n" + "2.Subtraction\n" + "3.Multiplication\n" + "4.Division\n" + "Enter operation number:");
            int n1 = scan.nextInt();
            scan.nextLine();

            switch (n1) {
                case 1:
                    op.add();
                    break;
                case 2:
                    op.diff();
                    break;
                case 3:
                    op.prod();
                    break;
                case 4:
                    op.quo();
                    break;
                default:
                    System.out.println("Invalid input");
                    break;
            }

            System.out.println("Try again? [Y/N]");
            ans = scan.nextLine().charAt(0);

        } while (ans == 'Y' || ans == 'y');
    }

}

然后netbeans有这个自动纠正导致这个:

package calc;

import java.util.Scanner;

public class Calc {

    private static char ans;

它添加了一个"私有静态字符;"我想了解更多如何修复我的代码。感谢

1 个答案:

答案 0 :(得分:1)

ansdo{ ... } while()循环中定义,但必须在外部定义,以使其可用于while中的条件。

所以:

char ans = 0;
do {
    Calc op = new Calc();
    Scanner scan = new Scanner(System.in);
    ans = 0;