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


ADVERTISEMENT

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

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

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

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

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

File Handling - Display Path Of The File In Text Field

May 6, 2014

I am facing a problem while executing a task. My task is to make such a code which will search for my source code file (abc.java) in all directories and then displays the code in textarea inside frame and along with that i also have to display the path of the file in text field. I have coded something but i am really not getting anywhere near my task.

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*
 
public class Lab extends JFrame {

[Code] ....

View Replies View Related

Catching Text Message From Exception

Apr 10, 2014

I can't catch the text message from a exception because ex.getMessage() is null.

Code is
 
try {
        .......
    } catch (Exception ex) {
            System.out.println("Error "+ex.getMessage());
            Logger.getLogger(Soap.class.getName()).log(Level.SEVERE, null, ex);
            statD.errMessage = ex.getMessage();
            statD.succes = false;
            return statD;
        }

And the program writes at the console:
 
Error null

Also on the console screen I can see the following message:

Apr 10, 2014 3:00:38 PM SoapUtils.Soap setPostVarsSEVERE: nulljava.lang.NullPointerException at SoapUtils.Soap.setPostVars(Soap.java:830)
Line 830 of Soap.java is inside the try {}.

Why is the ex.getMesage() null?

View Replies View Related

Write To Text Area Using Button - NullPointer Exception

Apr 25, 2015

I have problem with my simple program. I tried put some text in my text area using button1 but textListener in RighButtons is always null and it's give me NullPointerException.

WriteToArea - interface
public interface WriteToArea {
public void add_a(String text);
}
BaseFrame
public class BaseFrame extends JFrame{

[Code] .....

View Replies View Related

Highlighted Text In Try / Catch Block Is Throwing NullPointer Exception

Sep 15, 2014

If I put the highlighted text in try/catch block it is throwing NullPointerException , if I am using command line arguments then also it is showing the same exception.

public static void main(String []args)
args = null;
args[0] = "test";
System.out.println(args[0]);

View Replies View Related

Reading From Text File - Array Index Out Of Bounds Exception

Oct 21, 2014

I need to read from a text file given to us that has a list of books with authors names and book titles separated by an @ symbol for our delimiter. Here is the code I have right now, but it throws an ArrayIndexOutOfBoundsException at line 7...and I am unsure why?

import java.io.*;
import java.util.*;
public class Driver {
public static void main(String[] args) {
new Driver(args[0]);

[Code] ....

I realize that it must have something to do with my command line argument...but I am unsure what. Am I not entering the file name correctly?

View Replies View Related

Creating Simple Text Editor - Delete Selected Text Inside Text Area

May 13, 2015

This is the code that I wrote but I have two problem with two buttons one of them ... I want to delete the selected text inside the text Area which represented as b[8] and the other button that I want to select parts of the texts which represented as b[0]....

Here is the code..

package KOSAR2;
import java.awt.BorderLayout;
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;

[Code] .....

View Replies View Related

File Handling In A GUI

Apr 28, 2014

I created a GUI using Java with Buttons, Pictures and labels.When one of the buttons is pressed it increases the price, which can be seen by the labels increasing the necessary amount.What I would like to be able to do in my GUI is allow the user to record details of the sale and be able to display the sales of past customers to date, by this I mean when I click one of the buttons it will record the amount of that item into a file and when I press the another button, not the same button as the items, it will show the user the existing orders that have been taken in the past.

Here is my Code:

//Importing needed classes
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
 
[code]....

View Replies View Related

Handling IO Synchronization

Sep 16, 2014

I have a class (WriteExcel) which writes to an excel file. For those who don't know, Excel doesn't handle multiple access well (or at all).

I then have another class (WriteManager) which creates a new thread for each write command, and then calls a method from the WriteExcel class.

Other classes in my project calls methods from WriteManager to send their requests. My situation looks like this:

1) Thread 1: Someclass -> WriteManager.write1stPage(write) -> Creates Thread 2 -> WriteExcel.write1stPage(write) -> Start Excel Write
2) Thread 1: Someclass -> WriteManager.write2ndPage(write) -> Creates Thread 3 -> WriteExcel.write2ndPage(write) -> Start Excel Write
3) Thread 1: Someclass -> WriteManager.write3rdPage(write) -> Creates Thread 4 -> WriteExcel.write3rdPage(write) -> Start Excel Write
4) Thread 2: Finished writing and ready to save -> Throws exception due to multiple Excel access
5) Thread 3: Finished writing and ready to save -> Throws exception due to multiple Excel access
6) Thread 4: Finished writing and ready to save -> Throws exception due to multiple Excel access

I need to figure out a way to restrict access to WriteExcel until the writing is finished. So I need something like this:

1) Thread 1: Someclass -> WriteManager.write1stPage(write) -> Creates Thread 2 -> WriteExcel.write1stPage(write) -> Start Excel Write
2) Thread 1: Someclass -> WriteManager.write2ndPage(write) -> Creates Thread 3 -> Waits Until WriteExcel is free
3) Thread 1: Someclass -> WriteManager.write3rdPage(write) -> Creates Thread 4 -> Waits Until WriteExcel is free
4) Thread 2: Finished writing and ready to save -> Saves and frees WriteExcel
5) Thread 3: WriteExcel is free -> WriteExcel.write2ndPage(write) -> Start Excel Write
6) Thread 3: Finished writing and ready to save -> Saves and frees WriteExcel
7) Thread 4: WriteExcel is free -> WriteExcel.write3rdPage(write) -> Start Excel Write
8) Thread 4: Finished writing and ready to save -> Saves and frees WriteExcel

What is currently the best approach in java for handling this sort of situation?

View Replies View Related

Handling Sprite Overlapping?

Sep 16, 2014

The game I am working on now is an overhead game. Anyways I have a visual issues with the sprites where they overlap. I mean its normal to have sprites overlap but I do not want one to appear like it is walking on top of the other rather than the ground. The below is an image illustration the issue I want to address. (I am really good at drawing)

On the right you see what I want my sprites to do, but on left you see overlap in the way I am trying to avoid.

Now my approach to this problem is taking my array of monsters (a class that extends JLabels) and reordering them based on which monster is higher I make this occur at every run of my thread. It seems to me that if a monster is higher it should be added to the screen before the one that is lower. So I try to keep resorting the array of monsters at every iteration of my main game loop based on who is higher to account for the overlap

if (e.getSource() == follower){
c =0;
for (monster m: monsters) {
//Arrays.sort(monsters, new whoHigherComparator()); //I tried having the sort happen here
m.movingToPlayer(joe);//1
Arrays.sort(monsters, new whoHigherComparator());//2
layeredScene1.add(m, new Integer(3));//3

[code]...

The above is code that shows the majority of my games flow I will describe my flow with references to the commented lines above with [num] for better understanding of where I am coming from. Basically, there is a set number of monsters, the monster all locate and move to the player [1], then I attempt to sort the monster array based on height [2], then add my re-sorted monsters back onto the pane in order [3], then bumpers (a type that handle collision and make sure monsters don't overlap too much) attach the current monster [4], if bumpers are touching monsters arae moved away from each other until their bumpers are no longer touching [5], if the monster is moving leftwards set the animation to a leftwards walk [6], and likewise for rightwards walking [7]

By the way this is my comparator

public class whoHigherComparator implements Comparator<monster>
{
@Override
public int compare(monster m1, monster m2) {
System.out.println("comping?");
int h1 = m1.getY();
int h2 = m2.getY();
if (h1 < h2)

[code]...

At this point everything in my game flow works just fine, its just the annoying "walking on top of each other" effect that I am having trouble handling. And my attempt at this is line [2] & [3] from my game flow which seems like it would be an effective way to handle the "walking on top of another" effect but its surely not working. I also swapped the returns from my comparator but still no changes. It seems that maybe the array isn't being sorted and/or these changes are just not being reflected.

View Replies View Related

Handling Large Numbers

Oct 31, 2014

I found an exercise online to create a small program . I have this code that I have done so far:

import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong(); long b = sc.nextLong();
long count = 0; // counter

[code]....

The program should read the numbers a and b and list how many numbers between a and b are divisible by either 2, 3 or 5. If the user types the number 5 and then 8.... it would look at all the numbers in between - 5,6,7,8 and check if any of them are divasable by either 2,3 or 5. And since the numbers 5,6,8 are it would return the number 3 to the user..Now the problem is that this program only works for small numbers, but when I try to input numbers such as 123456789012345678 and 876543210987654321... it doesn't run at all.

So there needs to be a quicker way on how the program checks the numbers divisibility instead of checking each one. Here is where I am lost. How to fix the program that it will read bigger numbers such as a=123456789012345678 b=87654321098765432..There must be a quicker way ...something that can modify the code so it finishes in the matter of seconds not hours. Something that will fasten the process of checking if the numbers are dividable.

View Replies View Related

JSF :: Error Handling Via Servlet

Feb 19, 2014

On click of the ok button from a JSF page, a servlet is called on a new window. Servlet creates a CSV file , which will be streamed back for a download. Now if there is a error in the servlet, how can this be shown in the parent JSF?

View Replies View Related

Handling MVC Design With DatabaseDAO

Mar 31, 2015

I have done this a few times but I want to make sure I am doing it correctly. In other words creating a clean understandable program. Instead of posting code I will just talk about this is my plan:

Create a model (getter and setters)
Create a view (via swing)
Create a controller (pass the model and view in the parameter)

Database DatabaseConnection:
Use the singleton pattern

Database:
Create an interface called Database with all the queries I will need (insert, delete etc)
Create a class called DataBaseDAO and implement the interface database and get an instance of the DatabaseConnection.

Tying it all together:

In the controller should I use the "new" operator and create a new database class or extend the database class? I am thinking I should not do it in the controllers constructor but make a field if I use the "new" operator like:

private Database db = new Database();
Create a class called App
Create a new Model
Create a new View
Pass the view and model into the controllers parameter.

Am I on the right track? Is this messy? Is there a better way of doing it?

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







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