Calculate Sum Of Two Squares - Java And Exception Handling

Jun 19, 2014

I know I can calculate the sum of squares as such:

// SumSquares.java: calculate the sum of two squares
class SumSquares {
static int sumSquares(int a, int B)/>/> {
int asquare;
int bsquare;

[Code] ....

But how can I modify the code so that it inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares input values. And how would I go about using exception handling to ensure that the input values are in range and are legal integers.

View Replies


ADVERTISEMENT

Java And Exception Handling - Calculate Sum Of Squares (Input Values)

Jun 19, 2014

I know I can calculate the sum of squares as such:

// SumSquares.java: calculate the sum of two squares
class SumSquares {
static int sumSquares(int a, int B)/>/> {
int asquare;
int bsquare;

[Code] .....

But how can I modify the code so that it inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares input values. And how would I go about using exception handling to ensure that the input values are in range and are legal integers.

View Replies View Related

Calculate Tax Payments Based On Income And Filing Status - Handling Input Mismatch Exception

Nov 27, 2014

I have written the following code to calculate tax payments based on income and filing status :

import java.util.Scanner;
public class computeTax {
    public static void main(String[] args) {   
        Scanner input = new Scanner(System.in);
        // prompt for filing status
        System.out.println("enter '0' for single filer,");

[Code] ....

The while loop initiated on line 21 is there so that in case the wrong input is given at the prompt given in line 24, the program outputs "please type the right answer" with the command on line 254 before looping back to line 24 and prompting the user to enter his status number.  The program works as long as the input at line 28 is an integer.  Not surprisingly if the erroneous input here is not an integer, the program outputs the following error message :
 
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at computeTax.main(computeTax.java:28

To try to solve this I used the Try / Catch technique with the following version of the code : 

import java.util.Scanner;
public class computeTax {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // prompt for filing status       
        System.out.println("enter '0' for single filer,");

[Code] ....

View Replies View Related

Is Handling Instance Of Error Or Its Subclass Is Also Called Exception Handling

Mar 7, 2014

I have studied about the hierarchy of exception classes in which Throwable class comes at the top and two of its direct subclasses are Error and Exception..I just want to ask if in some code snippet we throw an instance of Error or its subclass within the try catch block then will that be also called "exception handling" ? I am asking this because Error class is not a child class of Exception therefore cant be said an Exception, therefore handling the same should not be called exception handling

View Replies View Related

What Handling Exception And Declaring Same Exception In Throws Clause Achieve

Jan 24, 2014

I was giving a quick skim to some tutorials on the internet where I have found the exception that is handled is also declared in the throws clause of the method wrapping the try-catch block. For a code representation consider the following:

public void methodName() throws IOException {
try {
...
} catch (IOException ex) {
.... TODO handle exception
}

}

View Replies View Related

Packages And Exception Handling?

Aug 17, 2014

Is there any connection between packages and exception handling in java. Means is it necessary to create a package before trying exception handling examples?

View Replies View Related

Exception Handling In A Constructer

Apr 22, 2014

Is there a special mechanism through which exception can be handled in a constructor?

Suppose while creation of an object there occurred an exception while creating an object, and the object is half constructed. How do we make sure we handle this kind of exceptions in a constructor?

View Replies View Related

Exception Handling For Strings?

Nov 25, 2014

For one of my last labs for the semester, my professor is having the class go back to our very first program and apply some of the exception handling that we just recently learned about. Here's my improved code so far:

Java Code: import java.util.*;
import java.lang.*;
public class Lab2Part1 {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);

[code]....

My code compiles fine, but even if I enter an integer or a double, it saves the number as a string, and prints that out as the name. Is there any way to get around this? Or do I need to use something besides a try-catch?

View Replies View Related

Exception Handling And Text I/0

Apr 19, 2015

I have been working on a problem dealing with exception handling and text input output for a few days now. The exercise is a two part exercise. The first part of the exercise I have to write a program to display the total salary for assistant professors, associate professors, full professors, and all faculty, respectively, and display the average salary for assistant professors, associate professors, full professors, and all faculty, respectfully using the what is posted on the [URL] .... Each line in the file consists of a faculty member's first name, last name, rank, and salary. The second part of the exercise I have to take my code and change it so that it

-lets the user enter the name of the file to be read,
-Uses a try-catch block to handle the FileNotFoundException displaying instead The file already exists..
... Use a second catch block to ignore any other exception thrown.
... Design your code so that, if the user enters a file that does not exist, the program prompts the user to enter again a file name.

and I need to Note: In order to catch the FileNotFoundException, you need to include import

java.io.FileNotFoundException;

package pkg14.pkg25;
import java.util.Scanner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

[code]...

View Replies View Related

How To Use Exception Handling As Base Class

Jun 17, 2014

I want to use my given code as base class

Java Code:

public static void file(String[] arg) throws IOException{
BufferedReader in;
String line;
try{
System.out.println("Reading word");
in =new BufferedReader(new FileReader("inp.txt"));

[Code] .....

View Replies View Related

Rectangle Class Include Try-catch And Exception Handling

Oct 18, 2014

The requirement is to write a rectangle class and a test class, which include try-catch blocks and exception handling. Exceptions, involving try, catch, throw, throws, and finally commands,how to write a code about basic things, but in the test class, it gives me specific width and height so that i dont konw how to write a try-catch blocks an exception handling in this test class.There is my two classes, they are separated.

public class Rectangle {
double width ;
double height ;
Rectangle(){
width = 1;
height = 1;

[code]....

View Replies View Related

How To Use File Input / Output In Addition To Exception Handling

Dec 2, 2014

I am trying to learn how to use file input/output in addition to exception handling... The problem is my textbook wrote this chapter for a version of Java that hasn't come out yet, so everything I do "according to the textbook" doesn't work. any feedback on correcting these exception errors because I am not sure what is causing them or how to fix them.

I was able to have it display the name of the book in the Book.txt file, but when I added the second part if the file doesn't exist, that's when the errors came up and it wouldn't compile.

import java.io.*;
import java.util.*;
public class DisplayBook
{
public static void main(String[] args) {
try {
File book = new File("Book.txt");
FileInputStream in = new FileInputStream(book);

[Code]...

These are the compilation error messages I am receiving: (I have managed to get it down from 7 errors to just 4, but now I'm stuck)

DisplayBook.java:15: error: unreported exception IOException; must be caught or declared to be thrown
while ((letter = in.read()) != -1) //if file exists, displays book title
^
DisplayBook.java:24: error: unreported exception FileNotFoundException; must be caught or declared to be thrown

[Code] ....

4 errors

View Replies View Related

Exception Handling - Block Cannot Modify Primitive Values

Sep 23, 2014

class MultipleReturn {
int getInt() {
int returnVal = 10;
try {
String[] students = {"Harry", "Paul"};
//System.out.println(students[5]); //if i remove comment

[Code] .....

View Replies View Related

10x10 Grid Java - How To Add Numbers To Squares

Mar 12, 2015

So I need to create a 10x10 grid for a snakes and ladders board, the board loads but i cant figure out how to add numbers to the squares. Here is my code :

import java.awt.*;
import javax.swing.*;
public class Board
{
//Creating the array
int[][] numbers=new int[10][10];
public static int rows = 10;
public static int columns = 10;
public static Color col1 = Color.green;

[Code] .....

View Replies View Related

Java File Handling

Aug 20, 2014

Assume we have 2 files that are input.txt and output.txt Input.txt has Name||Age||email||contact No||Name1||age1||email1||contact No1||name2||Age2||email2||contact no2||etc...

initially the output.txt does not have any record.using a java program we have to make it as

Names in the input file:Name,Name1,Name2,Name3 Ages in the input file:Age,Age1,Age2,Age3 email id in the file: email, email1, email2 Contact no in the file:contact no, contact no1,contact no2

View Replies View Related

File Handling In Java - Writing Objects In CSV

Dec 20, 2014

I'm doing this assignment in which i have to write some products in csv file...but as u can see in csv file two products are same "Cooking Oil"..so any method that can add two same product's quantity and their amount and write them in file

import java.util.*;
import java.io.*;
public class SalesbyTransactionMonth{
private static final String fileName = "Data.txt";
private static final String fileName1 = "sales_by_trans_month.csv";
String line = "";

[Code] ....

Attached image(s)

View Replies View Related

File Handling In Java - Modifying Specific Line

Mar 12, 2015

How to modify a specific line of a file in java. File name must be accepted from command line.

View Replies View Related

Handling Button Events In Eclipse Standard 4.4 / Java?

Jul 20, 2014

Code:
package button;
import javax.swing.*;
import java.awt.event.*;
public class Actions extends JFrame implements ActionListener
{
JPanel pnl = new JPanel();

[Code] ....

Errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type Actions must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)
event cannot be resolved
event cannot be resolved
at button.Actions.<init>(Actions.java:4)
at button.Actions.main(Actions.java:9)

View Replies View Related

Making Squares Of Numbers Without Multiplication?

Oct 22, 2014

so for my computer science class, we have the following problem:

In your documentation be sure to say which loop you thought was easier to implement for this program and why Write a program that produces the following outputs. The first line of output must be written using a For-Loop. The second, using a While-Loop and the third using a Do-Loop.

You look at the program and smile because you see that the series is just the numbers 1-10 squared...just one line is in reverse order. No problem! As you start typing you discover that the number 8 key on your keyboard is not working. For this program you are unable to use the multiplication key

So, back to the drawing board. By staring at the sequence a light comes on and you are able to quickly finish this program WITHOUT using mulitiplication (or the Math class/ solve with arithmetic operators +, - or / ) .

Sample output:

For Loop
1 4 9 16 25 36 49 64 81 100

While Loop
100 81 64 49 36 25 16 9 4 1

Do While Loop
1 4 9 16 25 36 49 64 81 100

I have the "for" done, but I did it with a "for" in the beginning but then had a multitude of nested "if" loops so that I could do 7*7=7+7+7+7+7+7+7

View Replies View Related

Determine All Of Perfect Squares Between 1 And 100 - Precision Error?

Mar 26, 2015

I am teaching myself Java and am trying to write a function that will determine all of the perfect squares between 1 and 100 but am running into a problem...

Here's my code:

package sqrroot;

public class SqrRoot {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double sroot, rerr;
int count = 0;
for(double num = 1.0; num <= 100.0; num++){

[Code] ....

and here is the output:

run:
0.0
1.0 is a perfect square.
0.0
4.0 is a perfect square.

[Code] ....

There are 49 perfect squares between 1 and 100.
BUILD SUCCESSFUL (total time: 6 seconds)

Which is clearly wrong. Is there something wrong with my code or is this due to inherent imprecision in the double type or the Math.sqrt function?

View Replies View Related

Fleet Of Ships - Drawing Squares In Graphic Context

Feb 20, 2014

Square:

package assignment1;
  
import java.awt.*;
public class Square
{
private double x,y; // Current position of the square.
private Color color; // The color of the square. 
private int side; // The side of the square
public Square() // constructor

[Code] .....

This is the square class, it draws an orange square that moves around in the applet viewer, works fine and as it supposed to do.

Ship:

package assignment1;
 
import java.awt.*;
 public class Ship
{
private Square[] fleetMembers; // declare fleetMembers as an array of Square
private int total = 5; // Max number of squares in fleet
private double x,y;
Ship() // Constructor

[Code] ....

This is my FleetOfShips code. It is supposed to be a set of ships moving around together, but for unknown to me reasons it doesn't work. It does compile without any problems but when I run the applet it doesn't do anything.

View Replies View Related

Unable To Fill Blank Squares On Minesweeper Game

Nov 12, 2014

I'm having trouble filling in the blank squares on a Minesweeper game. What I am trying to is, if a user clicks a square and that square(s) does not have a bomb in it, or adjacent to it, should be set to an empty square.

Here's my recursive method below:

public void revealZeros(){
for(int x = -1; x <= 1; x++)
for (int y = -1; y <= 1; y++){
Square zeroSquare = (Square)board.getSquareAt(xLocation+x, yLocation+y);
if (!(zeroSquare.SquareHasBomb)){
setImage("images/empty.jpg");
}
}
revealZeros();
}

I am traversing around the square that the user clicks on with the use of two for-loops. Getting the square at that location and then applying an empty square image. On that square.

The function should then recurse itself and go onto the next square, if the next square does not have a bomb or does not have an adjacent bomb.

I keep on getting an infinite recursion problem

View Replies View Related

Calculate Percent In Java

Jan 3, 2014

I would like to change the precent from *1.17 (17%) to calc of precent like this :

3% + 5% + 5$

For example :

The resault is 10$ - i want to get :

10$ +3%(0.3$) + 0.5% (0.51$) + 5$ = 15.81$

How i change this line to this calc

if(results[i].getSite()=='Xxx'&&XPrice==0)
{
XPrice =(results[i].getPrice() *1.17);
}
}

View Replies View Related

Calculate Coupon Discount In Java?

Feb 9, 2015

i finished up a project here and seem to be running into some issues. I figured its my notation, when i ask a user to enter a number, if its below 10, it should *only* print "No Coupon." but what appears to happen is that the program prints "No Coupon" Plus the "discount coupon and % of purchase."

import java.util.Scanner;
public class assign1c { /* Start of Class 1c */
static double cost;
static double coupon = 0;
static String x = "No coupon";
public static void main(String[] args) {
// TODO Auto-generated method stub

[code]...

View Replies View Related

Java Program To Calculate Diameter?

May 6, 2014

Assume the tanker is a cylinder of length 19.35 feet and volume 1320 gallons. What is the diameter in feet of the tanker truck? To solve this problem, write a Java program to calculate the diameter. For full credit, your Java application must follow these specifications.

1. The program must interactively input the capacity of the tanker in gallons and its length in feet. This should be done in the main method of your Tester class.

2. The input data should then be used to construct a TankerTruck object. You will need to write the TankerTruck class.

3. A TankerTruck method should be used by main to calculate the resulting diameter of the truck in feet.

4. Your program should use the standard Java constant for the math constant PI.

5. The output should be displayed using fixed-point notation, rounding to one decimal place of precision

View Replies View Related

Java Program Method To Calculate Distance

Feb 20, 2015

Write method distance, which calculates the distance between two points (x1, y1) and (x2, y2). All numbers and returned values should be of type double. Incorporate this method into an program that enable the user to enter the coordinates of the points, then calculate and display the distance by calling the method –distance.

I've tried numerous times to make it work and I'm on the right path, however I'm missing some things in the code to make my results look like this later on, which I've attached onto this post.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved