Showing posts with label numbers. Show all posts
Showing posts with label numbers. Show all posts

Dividing a Number in Java with Exception Handling

Description:

In this java code, we show you how to handle Exceptions when you divide two numbers by each other.

Code:

package com.javaproblems.divisionbyzerowithe;

import java.util.InputMismatchException;
import java.util.Scanner;

public class DivisionByZeroE {

 private static int ratio(int num, int denom) {
  return num/denom;
 }

public static void main(String[] args) {
 int numerator, denominator, result;
 @SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
 boolean continueLoop = true;
 do {
  try { 
  System.out.println("Please enter numerator: ");
  numerator = scan.nextInt();
  System.out.println("Please enter denominator: ");
  denominator = scan.nextInt();
    
  result = ratio(numerator, denominator);
  System.out.println(result);
  continueLoop = false;
  }
                catch(InputMismatchException e) {
    System.out.println("Exception: " + e);
    scan.nextLine();
  System.out.println("You must enter an int value."
                                    + " Please try again");
   } catch (ArithmeticException e) {
   System.out.println("Exception: " + e.getMessage());
   System.out.println("Zero is not a valid value. + " +
      " Please try again");
   }
   
   
  } while(continueLoop);
  
  
 }
}
 
Read More

Fibbonaci GUI calcualtor

Problem:

See the output

Output:



Prompt Picture Description




Solution:

//********************FibonacciNumbersApp.java*********/
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FibonacciNumbersApp extends JFrame {

 private JLabel inputLabel, resultLabel;
 private JTextField InputTextField;
 private JButton goButton;
 private int number;
 private JPanel northPanel, southPanel;
 private FibonacciWorker worker;
 public  FibonacciNumbersApp() {
  
  northPanel = createNorthPanel();
  southPanel = createSouthPanel();
 
  Container contentPane = getContentPane();
  contentPane.setLayout(new GridLayout(2,1));
  contentPane.add(northPanel);
  contentPane.add(southPanel);
 }
 
 private JPanel createNorthPanel() {
  JPanel panel = new JPanel();
  
  inputLabel = new JLabel("Get The Fibonnaci of: ");
  InputTextField = new JTextField(6);
  
  panel.add(inputLabel);
  panel.add(InputTextField);
  
  return panel;
 }
 
 private JPanel createSouthPanel() {
  JPanel panel = new JPanel();
  
  goButton = new JButton("Go");
  goButton.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     number = Integer.parseInt(InputTextField.getText());
    } catch (NumberFormatException e1) {
     resultLabel.setText("Input must be numeric!");
     return;
    }
    worker = new FibonacciWorker(number, resultLabel);
    worker.execute();
    resultLabel.setText("Calculating..");
   }
  });
  resultLabel = new JLabel("Ouptut will appear here: ");
  
  panel.add(goButton);
  panel.add(resultLabel);
  return panel;
 }

 
 
 public static void main(String[] args) {
  FibonacciNumbersApp demo = new FibonacciNumbersApp();
  demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  demo.setSize(350, 150);
  demo.setVisible(true);
  demo.setResizable(false);
  demo.setLocationRelativeTo(null);
  
 }
 
}
//********************FibonacciWorker.java*********/
import java.util.concurrent.ExecutionException;
import javax.swing.JLabel;
import javax.swing.SwingWorker;

public class FibonacciWorker extends SwingWorker<Long, Object> {

 private int number;
 private JLabel resultLabel;
 
 
 public FibonacciWorker(int number, JLabel resultLabel) {
  this.number = number;
  this.resultLabel = resultLabel;
  
 }
 
 
 @Override
 protected java.lang.Long doInBackground() throws Exception {
 
  return fibonacci(number);
 }
 
 @Override
 protected void done() {
  try {
   resultLabel.setText(get().toString());
  } catch (InterruptedException e) {
   resultLabel.setText("Interupted while waiting for result");
  } catch (ExecutionException e) {
   resultLabel.setText("Error encountred during execution");
  }
 
 }
 
 public  long fibonacci(int n) {
  if(n==0 || n==1) 
   return n;
  else 
   return fibonacci(n-1) + fibonacci(n-2);
 }
 
 
}
Read More

Checking whether a Number is a Power of 2 in Java

Problem:

Write a program that reads an integer n and checks whether n is a power of 2 (powers of 2 are 1,2,4,8,16,32, …). The output of your program is either “yes” or “no”.


Solution:

 import java.util.Scanner;

public class lauprob4
{
 public static void main (String[] args)
 
 {
  
  //Simple scanning of the number
  Scanner scan = new Scanner (System.in);
  
  System.out.print ("Enter an integer: ");
  
  int n = scan.nextInt();
  
  //Of course, a number is a power of n if its 
  //only divisors are 2 and 1, i.e. n=2^x * 1=2*2*2*2*...*1
  //this will make us exit the loop the second we find
  // out that the number isn't (still) divisible by 2
  //such as 8 which is a power of 2 and will eventually be
  //equal to one since with this loop 8 becomes 4, 2, then 1
  //Conversely, if it's not a power of two then we'll come out anyway
  // such as 6 becomes 3 which isn't divisible by 2 and so we exist
  //In any case we're gonna exit the loop eventually
  while (n % 2 == 0)
  { 
  //We just keep on dividing the number by 2 till we get out
  till we n /= 2;
  }
  //If our number really is a power of 2
  //then we'll eventually have to reach 1
  //for example, 16 becomes 8 which becomes 4 
  //which becomes 2 which becomes 1
  if (n == 1)
   
   System.out.println(n + " is a power of two");
  
  //if the number isn't a power of two, then the loop
  //would've changed the number to a number that isn't one
  else 
  
   System.out.println(n + " is not a power of two"); 
  
 }
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact