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


ADVERTISEMENT

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 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

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

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

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

Java Array Throws Exception For Multiple Values

Jan 3, 2014

int nRows = 0;
        for (EITest testCurr : testList) {
            testCaseListArray[nRows] = new Object[3];
            String testName = testCurr.getTestName();
            LOG.info("testName=" + testName);
            testCaseListArray[nRows][0] = testName;

[Code] ....

This throws null pointer exception because of array initialization error. I tried this:
 
int nRows=0;
        for(EITest testCurr: testList){          
            testCaseListArray[nRows] = new Object[3];
            String testName = testCurr.getTestName();
            LOG.info("testName=" + testName);
            testCaseListArray[nRows][0] = testName;

[Code] ....

But this is not complete solution.
 
2) I want to make this as a collection object such as array list instead of Array declaration.

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 - How To Reject Binary Values Longer Than 32 Bits (User Input)

Feb 24, 2014

I am designing a program in-order convert Binary to Decimal values with added features:

Rejecting binary values longer than 32 bits

Prompting the user to make multiple entries after completing the binary to decimal conversion of their first entry. I was trying to code this in Nested For Loops, but I don't know if I've really done that.

Here is what i have so far.

public class BinaryToDecimal {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String binary;
int decimal=0b10, i, rem;
boolean isBinary = true;
 
[Code] ....

View Replies View Related

Find Min And Max Values And Calculate Mean For Data Set

May 2, 2014

The first is MyArray Class (You can either use an array or an arrayList)Create a class called LastNameFirstNameMyArray according to the UML diagram. This class will allow a user to enter 5 integer values into an array(or object of ArrayList<Integer>). It contains methods to find min and max values and calculate the mean for the data set.

LastNameFirstNameMyArray - data[ ] : int (or data : ArrayList<Integer> )
- min : int
- max: int
- mean : double + LastNameFirstNameMyArray()
+ findMin() : void
+ findMax() : void
+ calculateMean(): void
+ toString() : String

Attributes:
data[]the array which will contain the values or data<Integer>the arraylist which will contain the values
minthe minimum value among the values in the arraylist
maxthe maximum value among the values in the arraylist
mean the arithmetic average of the values

Methods:
You need to implement the constructor LastNameFirstNameMyArray(), which populates 5 values. In addition, the constructor should call findMin() and findMax(), and also calculateMean().

Methods:
LastNameFirstNameMyArray()the constructor. It will allocate memory for the array (or arraylist) of size 5. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter value 1, value 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should account for this. For example, when the user enters value 1, it will be stored in indexed variable 0. The constructor should populate 5 integer values, call findMin() and findMax(), and also calculateMean().

findMin()this is a method that uses a for loop to access each data value in the array (or arraylist) and finds the minimum value. The minimum value is stored into min.

findMax()this is a method that uses a for loop to access each data value in the array (or arraylist) and finds the maximum value. The maximum value is stored into max.

calculateMean()this is a method that uses a for loop to access each data value in array (or arraylist) and add it to a running total. The total divided by the number of values (use the length of the array), and the result is stored into mean.
toString()returns a String containing data, min, max, and the mean.

Task #2 TestMyArray

1. Create a LastNameFirstNameTestMyArray class. This class only contains the main method. The main method should declare and instantiate a LastNameFirstNameMyArray object.
2. Compile, debug, and run the program. Then, it should print out the contents, the min, max, and mean of the data.

and the second is A theater seating chart is implemented as two-dimensional array of ticket prices, like this:

10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 20 20 20 20 20 20 10 10
10 10 20 20 20 20 20 20 10 10
10 10 20 20 20 20 20 20 10 10
20 20 30 30 40 40 30 30 20 20
20 30 30 40 50 50 40 30 30 20
30 40 50 50 50 50 50 50 40 30

Write a program that prompts the users to pick either a seat or price. Mark sold seats by changing the price the 0. When a user specifies a seat, make sure it is available. When a user specifies a price, find any seat with that price.

Note: Assume that if the user enters 1 for the row and 1 for the seat, the yellow marked sit will be sold.

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

Calculate Distance Between Two Points - All Numbers And Return Values Should Be Of Type Double

Jul 8, 2014

Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points.

Hints:

- The distance between two points can be calculated by taking the square root of

( x2 - x1 )2 + ( y2 - y1 )2

- Use Math class methods to compute the distance.

- Your output should appear as follows:

Type the end-of-file indicator to terminate

On UNIX/Linux/Mac OS X type <ctrl> d then press Enter

On Windows type <ctrl> z then press Enter

Or Enter X1: 1

Enter Y1: 1

Enter X2: 4

Enter Y2: 5

Distance is 5.000000

Type the end-of-file indicator to terminate

On UNIX/Linux/Mac OS X type <ctrl> d then press Enter

On Windows type <ctrl> z then press Enter

Or Enter X1: ^Z

View Replies View Related

Take Input From User And Calculate Value Of PI Using Formula

Sep 6, 2014

I'm supposed to take an input from the user and calculate the value of pi using this formula: 1/1 - 1/3 + 1/5 - 1/7 etc... so on alternating between minus and plus and denominator increasing by 2 every time. If the user inputs the number 3, then it should print (1/1 - 1/3 + 1/5 - 1/7 + 1/9) *4. The idea here is that the higher the input of the user is, the higher the equation will be close to pi.

This is what i have so far :

import java.util.Scanner;
public class Pi
{
public static void main(String[] args) {
double first = 1/1;
double second = 1/3;
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number to calculate how far you want the formula to perform: ");
double count = input.nextDouble();
}
}

This is literally all i have, i know i need a while loop and an if loop.

View Replies View Related

Calculate Factorials Of Numbers 1 Through 10 - Validating Input

Sep 13, 2014

I'm trying to write a program that calculates the factorials of the numbers 1 through 10, based on user input... My problem is that I don't know how to address the possibility of the user entering something other than a number. When I test the following code by entering a letter, I get an Input Mismatch exception. I'd like to be able to inform the user that the entry is invalid, and ask for another response. Here is my program thus far:

Java Code:

import java.util.Scanner;
public class Factorial {
public static String entryString;
public static char entryChar;
public static Scanner input = new Scanner(System.in);

[Code] ....

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

Input Length And Width - Calculate And Print Perimeter And Area Of A Rectangle

Feb 16, 2015

Create a program to input the length and width of a rectangle and calculate and print the perimeter and area of the rectangle. To do this you will need to write a Rectangle class and a separate runner class. Your program should include instance variables, constructors, an area method, a perimeter method, a toString method, accessor and mutator methods, and user input. Your runner class should include 3 Rectangle objects. One default rectangle, one coded rectangle, and one user input rectangle. All methods should be tested in the runner class.

This is my code:

import java.util.Scanner;
 public class Rectangle {
double length;
double width;
public Rectangle() {

[Code] ...

What have I done??? I have created this program using the few different resources with which I am supplied, but I don't understand the resources.

View Replies View Related

Calculate Total Sales After Each Football Game - JOptionPane (input / Output)

Mar 5, 2014

This specific assignment requires me to write a program that calculates the total sales after each football game. There are 4 types of tickets: box, sideline, premium, and general admission. After each game, data is stored in a file... then output the number of tickets sold and total sale amount. Format your output with 2 decimal places.

Okay I know there is a I/O section and wasnt sure where to post this. I need some insight on how to use file input and output as well ... Here is my program:

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class ticketsSold
{
public static void main(String[] args)
{
String BoxSeat;
String SideLine;

[Code] ....

View Replies View Related







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