Packages And Exception Handling?
Aug 17, 2014Is there any connection between packages and exception handling in java. Means is it necessary to create a package before trying exception handling examples?
View RepliesIs there any connection between packages and exception handling in java. Means is it necessary to create a package before trying exception handling examples?
View RepliesI 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 RelatedI 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
}
}
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?
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?
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]...
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] .....
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.
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]....
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
class MultipleReturn {
int getInt() {
int returnVal = 10;
try {
String[] students = {"Harry", "Paul"};
//System.out.println(students[5]); //if i remove comment
[Code] .....
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.
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] ....
I have GameConsole class with gamePlay(). There are two objects in this class that I want to access from a class in another package.
package blackjackControls;
public class GameConsole {
Player dealer; //both of these objects I am trying to bring over into the blackjackGUI package
Deck playingDeck;
public void gamePlay(){
[code].....
The dealer and playingDeck objects are giving me an error of unresolved. the way it is written I also get a static error on line 37. I know that I have not yet written in the actionEvent statement in the button constructor.
I was wondering what happens to the API packages I've imported at compile time. Are they compiled to classes and placed In the same file as the class containing the Import command ?
The reason I'm asking Is because I've noticed the src.zip file Is not In the JRE and since the JRE Is all that's needed to run an app , I'd like to understand what the import command does.
So I'm not entirely sure what to name my packages. Sometimes I have to many and it becomes overwhelming. Sometimes I don't have enough and I cannot keep my files organized. What is a good naming convention for Java packages?
View Replies View RelatedMy question is How to write a program to implement concept of creating user defined packages and importing the same? How to solve it.
View Replies View RelatedWhat to do with this JAVA code?
This is the code that I need to do without using the Joptionpane:
An Internet service provider has three different subscription packages for its customers:
Package A: For $9.95 per month 10 hours of access are provided. Additional hours are $2.00 per hour.
Package B: For $13.95 per month 20 hours of access are provided. Additional hours are $1.00 per hour.
Package C: For $19.95 per month unlimited access is provided.
Write a program that calculates a customer's monthly bill. It should ask the user to enter the letter of the package the customer has purchased (A, B, or C) and the number of hours that were used. It should then display the total charges.
This is what I have so far : Cannot use Joptionpaneshowinputdialog
/* A demonstration of how to use Decision Structures
import java.util.Scanner;
/**
This program demonstrates a switch statement.
*/
public static void main(String[] args)
{
char packageLetter;
int hoursUsed;
[Code] ....
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]....
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?
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.
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.
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 RelatedI 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?
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
I have a GUI that prompts the user for information. When they click 'submit', a new customer gets created from a class like so ...
Java Code:
public void actionPerformed(ActionEvent arg0) {
Customer customer = new Customer(); // New customer object
customer.name = view.getName();
customer.age = Integer.parseInt(view.getAge());
customer.ccn = view.getCCNumber(); mh_sh_highlight_all('java');
I am having difficulties validating my variables for nulls. For instance ...
Java Code:
// METHOD TO RETRIEVE TEXTBOX INPUT -- NAME
public String getName() {
String name = null;
if (jtfFirstName.getText() == null || jtfLastName.getText() == null || !jtfFirstName.getText().matches("[a-zA-Z]+") || jtfLastName.getText().matches("[a-zA-Z]+")){ // Validate name fields
JOptionPane.showMessageDialog(null, "<html><i>Improper Input Detected.</i>
[code]...
I can't seem to win with this. Whether the fields are filled in properly or not, I get the error message and the program continues to completion using the name "null".