简体   繁体   English

调试器停止工作

[英]Debugger stops working

My program needs to allow the user to input an employee's name and total annual sales. 我的程序需要允许用户输入员工的姓名和年度总销售额。 When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. 当用户完成将雇员添加到阵列后,程序应确定哪个雇员的销售额最高,哪个雇员的销售额最低。 It should then print out the difference between the two numbers. 然后应打印出两个数字之间的差异。

In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). 在下面的代码中,我有一个totalPay类,该类保存用户的年度销售输入(它包括先前分配中未在此处使用的其他变量和方法)。 The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. salesPerson类保存员工的姓名和totalPay对象,其中包括他们的年度销售额。 (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.) (我意识到这太复杂了,但是我正在修改我以前的作业,而不是从头开始。)

When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code. 当我运行此代码时,它允许我输入姓名和销售,但是当我输入“是或否”以添加另一名员工时,它崩溃并告诉我,在代码的第58行上有一个NullPointerException。

I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. 我已经运行了调试器(没有任何断点),它只是在代码中指出的第46行停止。 It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. 它没有给出错误消息,只是没有更新该变量,调试器的“进入”按钮显示为灰色,因此我无法再单击它们。 (I'm using NetBeans, if that's relevant.) (如果相关,我正在使用NetBeans。)

Any ideas would be much appreciated! 任何想法将不胜感激!

EDIT: Here is the output and error message. 编辑:这是输出和错误消息。

Name? 名称? captain America 美国队长

Input annual sales: 80 输入年销售额:80

Add another employee? 添加其他员工? yes or no 是还是不是

no 没有

Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58) Commission.Commission.main(Commission.java:58)处的线程“ main”中的异常java.lang.NullPointerException

package commission;
//Commicaion calulator


import java.util.Scanner;


public class Commission 
{
    public static void main(String args []) 
     {   
     salesPerson[] emps = new salesPerson[10]; //Employee Array
     String cont = "yes";
     String n="";
     double s=0;
     int i=0;
     salesPerson high = new salesPerson();
     salesPerson low = new salesPerson();

      // scanner object for input
        Scanner keyboard = new Scanner(System.in);

      //Enter in employee name 
     while (cont == "yes"){
        System.out.print("Name? ");
        n = keyboard.nextLine();
        emps[i] = new salesPerson();
        emps[i].setName(n);

         //Loop of yes or no entering more employees
        //If yes add another name if no continue with total Commision
        //Enter in the sales amount of commistion
        System.out.print("Input annual sales: ");  
        s=keyboard.nextDouble();
        emps[i].pay.annual = s;

        System.out.println("Add another employee? yes or no ");
        keyboard.nextLine();
        cont = keyboard.next(); //Line 46: Debugger stops here.

        if (cont =="yes")
            i++;
        if (i==9){
            System.out.println("You have reached the maximum number of employees.");
            cont = "no";
        }
     }

     i=0;
     for (i=0; i<emps.length; i++){
         if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
             high = emps[i];

         if (emps[i].pay.annual < low.pay.annual)
             low = emps[i];
     }

     double diff = high.pay.annual - low.pay.annual;
     System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());

    // Output table for composation with increments of $5000
//        int tempAnnual =(int) pay.annual;
//        for (i=tempAnnual; i<= pay.annual; i+=5000)
//            System.out.println(i+"   "+ pay.getReward(i));   
    }


  public static class totalPay
  {

      double salary=50000.0; //Yearly earned 50000 yr fixed income

      double bonusRate1=.05; //bounus commission rate of 5% per sale

      double commission; //Commission earned after a sale

      double annual; //Sales inputted

      double reward; // Yearly pay with bonus

      double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%

    public double getReward(double annual)
    {
       double rate;
       if (annual < 80000) 
        rate=0;
       else if ((annual >= 80000) || (annual < 100000 ))
        rate=bonusRate1;
       else 
         rate=bonusRate2;

      commission = annual * rate;

      reward=salary + commission; 

      return reward;
    }

  }

  public static class salesPerson
      {
    String name; //Employee Name
    totalPay pay = new totalPay();

    public void setName(String n) //Name
    {      
     name=n;         
      }
    public String getName()
    {
        return name;
    }
      }

  }

You create this array of max size 10: 您创建此最大大小为10的数组:

salesPerson[] emps = new salesPerson[10];

but only create and assign an object reference for each SalesPerson object entered. 但只能为输入的每个SalesPerson对象创建并分配对象引用。 Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. 由于仅输入1个名称,因此只有数组中的第1个输入有效,因此其余9个为空。 You then attempt to iterate through the entire array (emps.length is 10 ): 然后,您尝试遍历整个数组(emps.length为10):

  for (i=0; i<emps.length; i++){
         if (emps[i].pay.annual > high.pay.annual) 

which leads to the NPE when indexing the first null reference. 在索引第一个空引用时会导致NPE。 You need to change your loop to something like: 您需要将循环更改为:

  int numEntered = i;  //last increment

      for (i=0; i< numEnetered; i++){
             if (emps[i].pay.annual > high.pay.annual) 

It stops the debugger because it waits for your input using the keyboard. 它停止调试器,因为它等待使用键盘的输入。 If you type the input and hit enter, the debugger will continue from there on. 如果键入输入并按Enter,则调试器将在此继续。

By the way, your should read up on naming conventions and coding best practices for java 顺便说一句,您应该阅读有关Java的命名约定和最佳实践编码

Your debugger is stopped because it's blocked on input coming in from the Scanner. 您的调试器已停止,因为它阻止了来自扫描程序的输入。 This is specified in the documentation : 这在文档中指定

Finds and returns the next complete token from this scanner. 查找并返回此扫描仪的下一个完整令牌。 A complete token is preceded and followed by input that matches the delimiter pattern. 完整的标记在其前面,然后是与定界符模式匹配的输入。 This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true. 即使先前调用hasNext()返回true,此方法也可能在等待输入扫描时阻塞。

That aside, you're fortunate to have entered that code block at all. 除此之外,您很幸运完全输入了该代码块。 You're comparing Strings incorrectly , so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. 错误地比较了Strings ,因此乍一看,除非在某些特殊情况下,否则您似乎不会进入该循环。 This is also the reason that your NPE occurs; 这也是发生NPE的原因; you're initializing elements of your array under false pretenses ( == with a String), so: 您正在使用错误的借口( ==用字符串)初始化数组的元素,所以:

  • You may never initialize anything 您可能永远不会初始化任何东西
  • You may only initialize the first thing ( if (cont =="yes") ) 您只能初始化第一件事( if (cont =="yes")

I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. 我仅介绍了一些要点,但在大多数情况下,阻塞的IO是调试器停止的原因。 The other errors may become easier to see once you start using .equals , but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. 一旦开始使用.equals ,其他错误可能会变得更容易发现,但我鼓励您与同学,辅导老师或TA进行面对面的代码审查。 There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later. 这里对您的代码有很多误解,这将使以后调试或修复变得更加困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM