9 Replies - 1558 Views - Last Post: 14 March 2010 - 08:49 AM Rate Topic: ***-- 2 Votes

#1 AmateurC  Icon User is offline

  • D.I.C Head

Reputation: -5
  • View blog
  • Posts: 71
  • Joined: 12-June 09

Quitting a loop when needed

Posted 07 March 2010 - 11:21 PM

I am trying to write a program that allows a person to do division. The program will keep asking the user to input the divisor and dividend as many times as the user wants. If the user inputs a String instead of an integer or inputs 0 in the divisor, the program will display an error message. But if the user inputs "q" or "Q", the program will quit. But the compiler says that int cannot be dereferenced. What is my problem?
import java.util.* ;

public class DivisionPractice
{
  public static void main ( String[] a ) 
  {
    Scanner scan = new Scanner( System.in  );
    int num=0;
    int div=0;

    try
    { 
      while (num.charAt( "q") || num.charAt( "Q"))
      {
      System.out.print("Enter the numerator: ");
      num = scan.nextInt();
      System.out.print("Enter the divisor: ");
      div = scan.nextInt();
      System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) );
     } 
   }
     catch (InputMismatchException ex )
     {
      System.out.println("You entered bad data." );
      System.out.println("Run the program again." );
     }
     catch (ArithmeticException ex )
     { 
      System.out.println("You can't divide " + num + " by " + div);
     } 
  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Quitting a loop when needed

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 9025
  • View blog
  • Posts: 33,462
  • Joined: 27-December 08

Re: Quitting a loop when needed

Posted 07 March 2010 - 11:26 PM

Your problem lies in the condition of your while loop here while (num.charAt( "q") || num.charAt( "Q")), as you invoke the charAt() method on num, which is an int. Remember, you cannot invoke methods on variables of the primitive data types. In addition, num will not be able to store String literals. You should instead consider using a String temp variable to store Scanner input and parsing it to an int if it doesn't equal "Q". Lastly, the String charAt() method accepts an int param, not a String param.
Was This Post Helpful? 1
  • +
  • -

#3 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 73
  • View blog
  • Posts: 539
  • Joined: 19-February 10

Re: Quitting a loop when needed

Posted 07 March 2010 - 11:43 PM

Along with everything mac said previously, I would really recommend using a do-while loop instead as it checks after you run through, ensuring you get at least one loop. Then I would add another prompt where you get a String variable that feeds into a boolean. It would look like this:
String again;
boolean repeat = true;

try
    { 
      do
      {
      System.out.print("Enter the numerator: ");
      num = scan.nextInt();
      System.out.print("Enter the divisor: ");
      div = scan.nextInt();
      System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) );
      System.out.print("Do you want to run again? (Y or N)  ");
      again = scan.next();
      if(again.equalsIgnoreCase("N")
     {
          repeat = false;
     }
     else
     {
          repeat = true;
     }
     }  while(repeat); 
   }
     catch (InputMismatchException ex )
     {
      scan.next();
      System.out.println("You entered bad data." );
     repeat = true;
     }
     catch (ArithmeticException ex )
     { 
      scan.next();
      System.out.println("You can't divide " + num + " by " + div);
     repeat = true;
     } 
  }



I also added calls to scan.next() in the catch blocks because without them you get an infinite loop.

This post has been edited by zim1985: 07 March 2010 - 11:44 PM

Was This Post Helpful? 1
  • +
  • -

#4 AmateurC  Icon User is offline

  • D.I.C Head

Reputation: -5
  • View blog
  • Posts: 71
  • Joined: 12-June 09

Re: Quitting a loop when needed

Posted 08 March 2010 - 03:38 AM

View Postzim1985, on 07 March 2010 - 10:43 PM, said:

Along with everything mac said previously, I would really recommend using a do-while loop instead as it checks after you run through, ensuring you get at least one loop. Then I would add another prompt where you get a String variable that feeds into a boolean. It would look like this:
String again;
boolean repeat = true;

try
    { 
      do
      {
      System.out.print("Enter the numerator: ");
      num = scan.nextInt();
      System.out.print("Enter the divisor: ");
      div = scan.nextInt();
      System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) );
      System.out.print("Do you want to run again? (Y or N)  ");
      again = scan.next();
      if(again.equalsIgnoreCase("N")
     {
          repeat = false;
     }
     else
     {
          repeat = true;
     }
     }  while(repeat); 
   }
     catch (InputMismatchException ex )
     {
      scan.next();
      System.out.println("You entered bad data." );
     repeat = true;
     }
     catch (ArithmeticException ex )
     { 
      scan.next();
      System.out.println("You can't divide " + num + " by " + div);
     repeat = true;
     } 
  }



I also added calls to scan.next() in the catch blocks because without them you get an infinite loop.


When I tested your code, it looped when I inputted integers greater than 0. But when I tried inputting 0 as the divisor or inputted text instead of an integer, the program executed the Exception cases but stopped looping.
Was This Post Helpful? 0
  • +
  • -

#5 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 73
  • View blog
  • Posts: 539
  • Joined: 19-February 10

Re: Quitting a loop when needed

Posted 08 March 2010 - 03:56 AM

I see. Well I'm thinking, but honestly, it's 2:55 am where I am and I need to get up at 5:15. So I need to get some sleep.

Not that I can thinking of anything useful to say anyway...but I'll think about it in the morning and post what I come up with if someone else doesn't solve the problem already(which is highly likely).
Was This Post Helpful? 0
  • +
  • -

#6 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2695
  • View blog
  • Posts: 10,555
  • Joined: 15-July 08

Re: Quitting a loop when needed

Posted 08 March 2010 - 04:22 AM

View PostAmateurC, on 08 March 2010 - 05:38 AM, said:

When I tested your code, it looped when I inputted integers greater than 0. But when I tried inputting 0 as the divisor or inputted text instead of an integer, the program executed the Exception cases but stopped looping.


That's what it's supposed to do, a number cannot be divided by 0, so if 0 is your divisor, it will cause an ArithmeticException. Also, nextInt() takes an int, and if you don't, it will throw an InputMismatchException. Thats the way that its been coded.
Was This Post Helpful? 1
  • +
  • -

#7 AmateurC  Icon User is offline

  • D.I.C Head

Reputation: -5
  • View blog
  • Posts: 71
  • Joined: 12-June 09

Re: Quitting a loop when needed

Posted 08 March 2010 - 06:09 AM

View PostDogstopper, on 08 March 2010 - 03:22 AM, said:

View PostAmateurC, on 08 March 2010 - 05:38 AM, said:

When I tested your code, it looped when I inputted integers greater than 0. But when I tried inputting 0 as the divisor or inputted text instead of an integer, the program executed the Exception cases but stopped looping.


That's what it's supposed to do, a number cannot be divided by 0, so if 0 is your divisor, it will cause an ArithmeticException. Also, nextInt() takes an int, and if you don't, it will throw an InputMismatchException. Thats the way that its been coded.

I already provided the program on how to handle exceptions such as divide by zero. I want the program to continue looping until the user inputs "q" or "Q" to quit the program.

Of course, I could use an easier method on how to deal with problems such as divide by zero by simply saying:
if (div == 0)
{
   System.out.println("You cannot divide by zero!");
}
...


But I was assigned to write a program that deals with exceptions and this is where I am having difficulty in.
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 9025
  • View blog
  • Posts: 33,462
  • Joined: 27-December 08

Re: Quitting a loop when needed

Posted 08 March 2010 - 06:54 AM

View Postmacosxnerd101, on 08 March 2010 - 02:26 AM, said:

In addition, num will not be able to store String literals. You should instead consider using a String temp variable to store Scanner input and parsing it to an int if it doesn't equal "Q".


You might want to re-read my suggestion from earlier. :)

String temp = scan.next();
if(temp.equalsIgnoreCase("Q")){
   //quit
}
else{
   //parse temp to an int
}



Also, note that Integer.parseInt() throws a NumberFormatException for an invalid String instead of an InputMismatchException like Scanner does.

Edit: I misspelled String.

This post has been edited by macosxnerd101: 08 March 2010 - 04:48 PM

Was This Post Helpful? 1
  • +
  • -

#9 AmateurC  Icon User is offline

  • D.I.C Head

Reputation: -5
  • View blog
  • Posts: 71
  • Joined: 12-June 09

Re: Quitting a loop when needed

Posted 13 March 2010 - 11:58 PM

I managed to make some modifications to my program. The program loops several times when I enter legal integers and quits when I input words starting with "q" or "Q". However, when I input a zero into the divisor or words that do not start with "q" or "Q", the program quits instead looping.
import java.util.* ;

public class DivisionPractice
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in  );
    int userInput = 0;
    int num;
    boolean isBad;
    String test;
    int div;
    boolean isQuit;
    
   try
    {
     isQuit = false;
     while (!isQuit)
     {
      System.out.println("Enter numerator: ");
      scan = new Scanner(System.in);
      userInput = scan.nextInt();  
      num = userInput;
      isBad = false;
      System.out.println("Enter divisor: ");
      userInput = scan.nextInt();  
      div = userInput;
      isBad = false;
      int quotient = num / div;
      System.out.println("The quotient is " + quotient);
    }
   }
    catch(InputMismatchException ex)
    {
     test = scan.nextLine();
     if  ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q') )
     {
        System.out.println("Good-bye!");
        isQuit = true;
     }
     else
     {
       System.out.println("Invalid input!");
       isQuit = false;
     }
    }
    catch (ArithmeticException ex)
    {
      System.out.println("You cannot divide by zero!");
      isQuit = false;
      
    }
  }
}


Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 9025
  • View blog
  • Posts: 33,462
  • Joined: 27-December 08

Re: Quitting a loop when needed

Posted 14 March 2010 - 08:49 AM

Your problem is that you put your loop to get input within the try-block. So as soon as an Exception is thrown, you break out of the try-block and the catch block is executed. And since there is no loop around the try-catch blocks, your code will exit.


Quote

You should instead consider using a String temp variable to store Scanner input and parsing it to an int if it doesn't equal "Q".

Again, I would not use try-catch with InputMismatchException. Instead, I would use a String temp variable as I've suggested twice before b/c it gives you tighter control over your code so you can test for values without worrying about Exception handling.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1