0

The statement says:

A pen manufacturer has automated quality control of its products. When a pen meets the minimum requirements, the unit in charge of quality control writes the letter 'S', otherwise writes 'N' and when finalize writes 'F'. Consider that after each these characters of the device introduces a "intro / enter." Write a program that calculates the percentage of pens that have not met the minimum requirements of manufacture. Supposed the device writes the data correctly. (Boligrafos.java).

I put this code:

import java.util.Scanner;

  public class Boligrafs {

    public static void main ( String [] args ) {

    Scanner sc = new Scanner (System.in);

    String estat;
    int contador1 = 0, contador2 = 0;
    float percentatge;

    System.out.println("Introdueix un estat del boligraf");
    estat = sc.next();

    while (estat == "S" || estat == "N") {
      if (estat == "S"){
        System.out.println("Introdueix un estat del boligraf");
        estat = sc.next();
      }
      else if (estat == "N"){
        System.out.println("Introdueix un estat del boligraf");
        estat = sc.next();
        contador1 = contador1 + 1;
      }
    contador2 = contador2 + 1;
    }
    if (estat == "F") {
      System.out.println("Has finalitzat");
    }

    percentatge = 100 * contador1 / contador2;
    System.out.println("El percentatge es:"+percentatge+"%");

  }
}

I can't understand the error because i think my program is correct:

Exception in thread "main" java.lang.ArithmeticException: / by zero at Boligrafs.main(Boligrafs.java:32)

David
  • 27
  • 1
  • 7

2 Answers2

2

The problem is that you're using == to compare strings that you entered against strings that are hardcoded in your program. Replace all == by .equals() and the problem should be solved.

For example, replace estat == "S" by estat.equals("S")

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
  • I might be wrong, but == should work for his case, since he doesn't call a new String constructor. – DeiAndrei Nov 12 '14 at 12:20
  • 2
    The code `sc.next()` returns a new string every time. The `==` operator when applied to Strings returns true if and only if the memory address of the two strings is the same. – Mike Laren Nov 12 '14 at 12:24
0

as suggested by Mike Laren you use estat.equals("S") for String value comparison and for calculating percenatge put your calculaiton part code inside if else part as below.

if(contador1>0 && contador2>0)
 {
   percentatge = 100 * contador1 / contador2;
 }
 else
 {
   System.out.println("your error message");
   percentatge=0.0;
 }
mady
  • 119
  • 1
  • 3
  • 12