与Scanner.nextLine严重混淆

时间:2016-05-06 03:16:05

标签: java string static

所以我自然地用这个主题检查了其他问题,但是我无法找到我理解的问题的答案,因为我是一个完整的,完全的编码初学者。我正在为我的班级(学校)写一个代码,但是看到它是晚上11点11分,我的老师睡着了。这是我的代码:

import java.io.*;
import java.text.*;
import java.util.Scanner;
import java.util.Random;  
import java.util.ArrayList;

public class Unit3_lesson3_1 {

    Scanner scanner = new Scanner(System.in);

    public void main() {
        // code starts here:
        System.out.println("This is a program that tells you what your answer is");

        System.out.println("Enter the first number ");
        int num1 = scanner.nextInt();

        System.out.println("Enter the second number ");
        int num2 = scanner.nextInt();

        System.out.println("Enter your operator. M for mulitiplication, D for division, A for adding, and S for subtraction.");
        String op = Scanner.nextLine(); //this is where my error occurs

        if (op.equalsIgnoreCase("M")) //this is to check what the string input is
            System.out.println("The product is: " + num1*num2);
        else if (op.equalsIgnoreCase("D")) 
            System.out.println("The product is: " + num1/num2);    
        else if (op.equalsIgnoreCase("A")) 
            System.out.println("The product is: " + num1+num2);
        else if (op.equalsIgnoreCase("S")) 
            System.out.println("The product is: " + num1-num2);
    }
}

上面的Scanner.nextLine()给出了一个错误,指出无法在静态上下文中引用非静态方法。我真的需要一些帮助才能理解为什么,希望你能用外行的方式回答,就像我说的那样,我是一个完全的初学者。

0 个答案:

没有答案