我的代码中有一个nullPointerException,我不知道如何解决

时间:2015-02-12 04:32:15

标签: java nullpointerexception

我正在编程课程中,我正在开发一个计算并显示您必须完成的作业问题的程序。这个程序考虑到你的教授可能会分配古怪的东西,比如只做其他奇数或每个奇数。这个程序必须有两个用不同的java文件编写的类,以强化我们在课堂上一直在做的工作。当我编译程序时,没有错误。当我尝试运行它时,这就是我得到的错误:

显示java.lang.NullPointerException

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)


import java.util.*;

public class HomeworkCounter
{
  public void main(String[] args)
  {
    Operation operations = new Operation();
    Scanner keys = new Scanner(System.in);
    String eoo = "", eo = "";
    System.out.print("Is it EOO?");
    keys.nextLine();
    eoo = keys.nextLine();
    if (eoo.equals("yes"))
      operations.everyOtherOdd();
    System.out.print("Is it every odd?");
    eo = keys.nextLine();
    if (eo.equals("yes"))
      operations.everyOdd();
    else
      operations.allProblems();
    System.out.println("You have" + operations.total + "problems to finish.");
    keys.close();
  }
}

import java.util.Scanner;

public class Operation
{
  private int start = 0;
  private int finish = 0;
  public int total = 0;
  private int extras = 0;
  Scanner keys = new Scanner(System.in);

  public int everyOtherOdd()
  {
    System.out.print("Please enter your starting number: ");
    start = keys.nextInt();
    total = start;
    System.out.print("Please enter your last number: ");
    System.out.print("How many 'extra' problems do you have?");
    extras = keys.nextInt();

    while (total <= finish)
    {
      System.out.println(total);
      total = total + 4;
    }
    total = total + extras;
    return total;
  }

  public int everyOdd()
  {
    System.out.print("Please enter your starting number: ");
    start = keys.nextInt();
    total = start;
    System.out.print("Please enter your last number: ");
    System.out.print("How many 'extra' problems do you have?");
    extras = keys.nextInt();

    while (total <= finish)
    {
      System.out.println(total);
      total = total + 2;
    }
    total = total + extras;
    return total;
  }

  public int allProblems()
  {
    System.out.print("Please enter your starting number: ");
    start = keys.nextInt();
    total = start;
    System.out.print("Please enter your last number: ");
    System.out.print("How many 'extra' problems do you have?");
    extras = keys.nextInt();

    while (total <= finish)
    {
      System.out.println(total);
      total = total + 1;
    }
    total = total + extras;
    return total;
  }
}

我对错误所在的地方感到难过。 提前感谢您的回答。

2 个答案:

答案 0 :(得分:2)

看起来您正在使用的编译器无法找到main方法,因为它未声明为static。改为:

public static void main(String[] args)

答案 1 :(得分:1)

public static void main(String[] args)

主要方法需要static!或者编译器不知道程序的起始位置,将其视为程序的入口点。