Exception Errors In Simple Program?

Mar 26, 2015

I'm trying to read lines from a textfile and count all the words using String Tokenizer. However I keep getting an error "Unhandled exception type FileNotFoundException" on my IDE(Eclipse) referring to lines 13 and 8. When I let the IDE automatically, and I've even tried typing this manually, insert a try-catch block more errors show up concerning inputFile. When I insert the throws FileNotFoundException for each method it compiles but after running it gives me a FileNotFoundException for textfile.txt. What's even more interesting is that when I copy the .java file out of the IDE project folder, place it in a random empty folder on the Desktop with the textfile.txt, and try running it through command line, it gives a NoSuchElementException: No line found.

import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;

[Code].....

View Replies


ADVERTISEMENT

Getting NullPointer Exception Error In Simple ArrayList Program

Mar 21, 2015

I am creating a simple ArrayList program that would enable one to input their username to it using a scanner. However, i am getting this error: "Exception in thread "main" java.lang.NullPointerException

at home.Members.addUser(Members.java:16)
at home.Main.main(Main.java:14)"

Here is the code! :

Main.java class
Java Code: import java.util.Scanner;
public class Main {

[code]....

View Replies View Related

Simple Mathematical Computation Not Working - Receiving Errors

May 3, 2015

Here's my code:

System.out.println((3 / 1.5) + 42(3 + 3));

I don't understand what I'm doing wrong. I'm receiving these errors:

PrintFunction.java:8: error: ')' expected
System.out.println((3 / 1.5) + 42(3 + 3));
^
PrintFunction.java:8: error: not a statement
System.out.println((3 / 1.5) + 42(3 + 3));
^
PrintFunction.java:8: error: ';' expected
System.out.println((3 / 1.5) + 42(3 + 3));

I'm using Sublime Text and JDK 8.

View Replies View Related

Writing Binary Search Program And Keep Getting Errors

Feb 24, 2014

Java Code:

public class Search
{
public static final int NOT_FOUND = -1;
public static int binarySearch( int [ ] a, int x )
{
int low = 0;
int high = a.length - 1;
int mid;
while ( low <= high )

[Code] ....

I keep getting illegal start of expression at ={-3,10,5,24,45.3,10.5}

It says I have 12 errors and I have tried so many things to fix it and I just don't know what to change to make it work.

View Replies View Related

Phone Network - Program Compile But Has Several Runtime Errors

Apr 4, 2014

The first 4 class below are the main classes while the last class is the testing class. I got it all to compile but for whatever reason there are several runtime errors. I have spent hours trying to figure out what they are, but I was only able to eliminate a few.

import java.util.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import java.lang.*;

public class PhoneNetwork {

[Code] .....

View Replies View Related

JGrasp - Errors In Writing A Program For Checking And Savings

Sep 19, 2014

Here is the objective of the assignment:

Quote : A bank in your town updates its customers' account at the end of each month. The bank offers two types of accounts: savings and checking. Every customer must maintain a minimum balance. If a customer's balance falls below the minimum, there is a service charge of $10 for savings accounts and $25 for checking accounts. If the balance at the end of the month is at least the minimum balance, the account receives interest as follows:

- Savings accounts receive 4% interest.

- Checking accounts with balances of up to $5000 more than the minimum balance receive 3% interest; otherwise, the interest is 5%.

Write a program that reads a customer's account number (integer), account type (character: s for savings or c for checking), minimum balance that the account should maintain, and the current balance. The program should then output the account number, account type, current balance, and an appropriate message.

Your program should only allow 'c', 'C', 's', or 'S' as valid input, any other character for the account type should result in an error message. Format your monetary output to two decimal places, and use constants for all the above constant values.

Sample output:
Please enter your account number (int), account type (char), minimum balance, and current balance:
46728 S 1000 2700
Account Number: 46728
Account Type: S
You have earned 0.04 interest on your account.
Current Balance: $2808.00

[Code] .....

Invalid account type!

View Replies View Related

Grading System Program - No Syntax Error But Got Compile Errors

May 23, 2015

Netbeans do not detect any syntax errors, but I when I check the build it retuned areas they were a few; It's a simple program name 5 people, gade them then do final calulatoins it's called "grade tool.

heres the code

package gradingapplication;
import java.util.Scanner;
public class GradingApplication {
public static double score(double score){
if(score >= 90){
System.out.println("A");

[code]...

~Problems~

1. It has no gui, I don't know java fx, is java groove used? awt is useful for creating spam bots in robot class, I know it's not very useful but it's so much fun.

2. the sections where I use the scanner.

View Replies View Related

Retrieving User Input String From Keyboard - Program Errors (try / Catch)

Sep 23, 2014

I need to design, implement, and test a program to input and analyze a name. The program begins by retrieving a user input string from the keyboard. This string is intended to be the user's name. These are the errors we have to search analyze the user input for: No blanks between names firstName and lastName, Non-alphabetic characters in names, Less than two characters in first name, and Less than two characters in last name. Each of these errors must be thrown. All exceptions must be derived from a programmer-defined class called NameException. Each exception should use a detailed message to differentiate among the file types of errors.

This is the format of my NameException class, is the format itself correct? I will fill in the details of each exception I am just wondering if that is how I should set it up.

public class NameException extends Exception {
private String firstName, lastName;
public NoBlanksException(String firstName,String lastName) {
}
public NonAlphabeticalCharactersException(String firstName, String lastName) {

[Code] .....

I was told not to try and catch thrown errors in the main method, would I just create another method in the Driver class to take care of that then?

View Replies View Related

Running A Simple GUI Program

Nov 23, 2014

I'm getting back into the swing of things with Java after using I'm asked to utilize a simple GUI in order to take in the starting data, I cannot seem to get this to work. I'm getting this error Exception in thread "main" java.lang.NullPointerException

at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Input.buildPanel(Input.java:53)
at Input.<init>(Input.java:27)
at InputDemo.main(InputDemo.java:5)

I've created two classes

import javax.swing.*;
public class Input extends JFrame {
private JPanel panel;
private JLabel messageLabel;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JTextField shiftHrs;

[code]....

View Replies View Related

Simple Three Button Program

Dec 14, 2014

I have my program set up I thought correctly. When I click the buttons, nothing is happening.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RobertMaloneChapter18 extends JFrame
{
//set final sizes for window
private static final int WIDTH = 300;
private static final int HEIGHT = 200;

[code]....

View Replies View Related

Simple Pyramid Program

Jun 28, 2014

I was learning Java and there was this exersize to construct a simple pyramid of prespecified height and width. The program i wrote is turining up with the wrong result.

package asgn2;
import acm.graphics.*;
import acm.program.*;
public class pyramid extends GraphicsProgram {
private static final int BRICK_WIDTH = 30;
private static final int BRICK_HEIGHT = 12;
private static final int BASE_BRICKS =14;

[code]...

View Replies View Related

Simple Averaging Program Using Two Different Classes?

Apr 9, 2014

This is a simple project that i was using to test my current java knowledge (kinda like revision) and for that i used two classes to make a simple averaging program. i know i0m making it more difficult but like i said i'm testing myself but i come up with an unexpected error. Here's the code:

- 1st Class

import java.util.Scanner;
public class Main {
public static int num;
public static int total = 0;
public static int average;

[Code].....

Now the problem is after inputing the numbers it doesn't give me the average but the value of 0.

View Replies View Related

Simple Encryption / Decryption Program

Nov 1, 2014

I have to write an encryption/decryption program for a sentence entered by the user that uses arrays. Here is my code so far. I'm kind of lost on what to do next in the code.

import java.util.Scanner;

/*Program that encrypts then decrypts a sentence
Encryption
*/
public class Encryption extends java.swing.JFrame{

[code]....

View Replies View Related

Make A Simple Calculator Program

Mar 11, 2015

i am working on my assignment in Compro 2, we are ask to make a simple calculator program

here's my code;

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;

[code]...

View Replies View Related

How To Make A Simple Connect Four Program Without GUI

Nov 19, 2014

My code below is trying to make a connect four program without GUI. I'm having trouble with getting the players to make their moves. What should I put in my "makeAMove" method...

Java Code:

public class Connect

final static int MAXROW = 6;
final static int MAXCOL = 7;
public static void main(String[] args){

[code]....

View Replies View Related

Simple Vending Machine Program

Jan 22, 2014

I am having a difficult time writing what started out as a simple vending machine program. As I go on though, it seems that I'm overcomplicating it and it is getting messy, so I have resorted to the forum before I really get off the path. how to clean it up? I'm going to list a few of the problems I am having with the code below:

1. The user is supposed to enter his/her money and the program is to read each value separately (Do-While loop) and keep a running total of the money entered. I can't seem to get the right code format to do this. I was trying to do this with the variable total and so that is why the total exists in the switch statement, but it did not work.

2. In the second Do-While statement, is there a way to kick back an error when their are insufficient funds to purchase an item? Instead of getting a negative change return.

package practice;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
double count, total;
int item;
//Display Available Options To Customer
Scanner input = new Scanner(System.in);
System.out.println("*VENDING MACHINE*");

[code]....

View Replies View Related

Simple 2D Optics Simulation Program

Sep 13, 2014

I'm very new to Java (I literally started learning it yesterday) and I've been working on a simple program that's meant to simulate interactions between optics objects and light rays.

Everything has been going really well, except that my mirrors only reflect the first ray that comes in contact with them.

Here's a screenshot : 2014-09-13 at 7.39.23 PM.jpg

I wrote 7 classes:

Main class to create the optics objectOptics class. the most important class that uses a recursive function to detect the nearest intersection point of a ray with the nearest optics object. It then calculates a reflected ray and inputs it back into the function until no intersections are found or the max recursion depth is met.Ray. creates a rays (in parametric form O + tD where O is the origin, D is the direction and t is a non-negative scalar)Object. empty abstract class used for polymorphism (so when i add more optics objects like prisms and lenses they'll share the object type)Mirror. Basically a line segment created with the Line classLine. Creates a line segmentDraw. JComponent with paintComponent function that loops through an array of shapes and draws them to the screen.

What I know so far is that the problem boils down to the checkRay() function in the Optics class. When a mirror has already reflected a ray, the line:

Intersection sec = new Intersection(ray,(Mirror)obj);

creates an intersection with a null point.

I debugged it line by line and found the problem was that my variable 't' (that is the parameter for the parametric line which represents the mirror) in the Intersection class got big values when it's meant to be between 0 and 1 (since it's a line segment), which resulted in the function returning null (as it should when 't' is not between 0 and 1).

I've confirmed with tests that this has nothing to do with the specific mirror or angle of incidence. It only occurs when a mirror has already been intersected with by a ray.

I've found out that my function:

public PVector getNormal(PVector D){
D.normalize();
return new PVector(D.y,-D.x);
}

Changes the value of the 'D' PVector of the mirror inside my 'objects' ArrayList. How can it access the private PVector 'D' from outside the Mirror class? This normalization to the direction vector is what causes the Intersection class to return null the second time around!

The problem was that in the getNormal function, the input vector argument was a reference to the 'D' vector for the mirror in my 'objects' ArrayList so the .normalize() function acted upon the original vector, changing it's value and screwing things up. The two classes I talked about:

Optics: (note line 64. this line returns a null intersection when it shouldn't)

package ofer.davidson;
 import java.util.ArrayList;
 public class Optics {
 //Arrays to store all the optics objects and rays that are created
ArrayList<Object> objects;
ArrayList<Ray> rays;
 
[Code] .....

Also why doesn't my background turn white??

View Replies View Related

Make Simple Program Which Takes In Argument?

May 12, 2015

So I'm trying to make a simple program which takes in an argument (target) and then looks through an ArrayList of strings. If it finds a string that begins with (target) then it will return the index of that string. If it doesn't find a string which begins with (target) then it will return -1 instead.

For some reason, the program is always returning -1, rather than the index of the string within the ArrayList when there is one which matches the search criteria.

Here is the code:

public int getIndex(ArrayList<String> text, String target)
{
int i = 0;
int index = -1;
boolean found = false;

[Code].....

View Replies View Related

Program To Simulate Operation Of Simple Robot

Apr 26, 2015

Write a program to simulate the operation of a simple robot. The robot moves in four directions: Forward, backwawrd, left, and right. The job of the robot is to move items and place it in the right slots in each station. There are 8 stations plus the pickup station. Pick up station is the initial start where the robot picks the items. 8 items can be placed on each station. The nearest station must be filled before placing items on the next station. The items are marked with identification or serial numbers. The items with odd serial number go to the right and items with even number go to the eft. The last slot, number 7 is reserved for light items which are less than 80kg. The serial number is a five digit number, the MSB digit 5 indicates that the product must be placed in the fifth station which is keeping the product at 20 degree F.

View Replies View Related

Creating A Program That Calculates Simple And Compound Interest

Aug 12, 2014

I need getting started designing and creating a program that calculates simple and compound interest. Simple interest in this case means that interest is only applied to the original amount. For instance, if a person deposits $1000 at 10% annual interest, then after one year they would have $1100 (the original $1000 plus the $100 interest) and after two years they would have $1200 (the original $1000, plus the $100 earned the first year, plus the $100 earned the second year).

With compound interest, the interest is applied to all money earned. So, starting with $1000 at 10% annual interest, after one year the user would have $1100 (the original amount plus $100 interest) and after two years the user would have $1210 (the $1100 they started with at the beginning of the year plus the $110 interest).

The requirements of this program are:

-Create a class that will hold methods to calculate the interest. Do not include the main method in this class.
-In the class that is used to calculate the interest, include a method to print to the screen, by interest period, the starting amount for the period, the interest earned for the period, and the total amount at the end of the period. Note that each period represents the time frame for how often it is updated. If annual is selected the period is every year. If it is semi-annual it is every six months. If it is quarterly it is every three months.
-Create a demo class that will use your interest calculation class. Prompt the user for the original amount, the type of interest (simple or compound), the annual interest rate, and whether it is updated annually, semi-annually, or quarterly. Use method calls to your calculate interest class to do all calculations and display the result. Loop the program until the user chooses to quit.

Sample output ($10000 initial investment, 10% simple interest, annual, for 4 years):

Period Beginning Amount Interest Earned Ending Amount
1 10000.00 1000.00 11000.00
2 11000.00 1000.00 12000.00
3 12000.00 1000.00 13000.00
4 13000.00 1000.00 14000.00

View Replies View Related

Simple Chat Program With Client / Server EOFException

Feb 13, 2015

When I Start Server and login from client everything goes fine but as soon as I want to send amessage or use showIn or even logOut .

Get below error

Exception creating new Input/output Streams: java.io.EOFException

View Replies View Related

Simple Logic Error In Cipher-shifting Program?

Feb 8, 2015

I was tasked with creating a program that encrypts a line of text (for example, CANDY) by shifting the letters X amount of times. For example, if the user inputs the sentence CANDY and selects a shift of 5, the output would be: HFSID. I got this part working fine. The issue I am having is with the decryption part of the program.

This is simply the reverse of the above, as the user would enter the phrase HFSID, with a shift of 5, and the program would output: CANDY. It works fine, all except for one letter, being the "F" letter. With my code, when I enter the above word to be decrypted it outputs: C[NDY

Obviously, that [ bracket is not an 'A'. I realise the issue falls with the equation, Here is my code:

public class SimpleEncryption {

/**
* @param args the command line arguments
*/
static int answer;
public static void main(String[] args) {
String cipher = JOptionPane.showInputDialog(null, "Please enter a sentence or word that you wish to encode or decode. This program uses"
+ " a basic cipher shift.");

[code]....

View Replies View Related

Simple Program In Java (Eclipse) That Converts Fahrenheit To Celsius

Apr 10, 2014

I've made a simple program in Java (Eclipse) that converts Fahrenheit to Celsius.The class is:

Java Code: package ehu.student;
public class ConversorTemperaturas {
/*--------------------------------------------------------------*/
/*Clase que dado una temperatura en Fahrenheit la canvierte en C*/
/*--------------------------------------------------------------*/
public float farenheit2celsius (float d){
float celsius, aux;

[code]...

When I write t.farenheit2celsius(25.6), appears the following error: "The method farenheit2celsisus(float) in the type ConversorTemperaturas is not applicable for the arguments (double)"If i change in the class the type float for double there is not problem. Why can't i use the type float?

View Replies View Related

Simple Program Giving Negative Result For Amount Of Calculations Done

Mar 5, 2014

Why this extremely simple program seems to be giving me a negative value for amount of calculations done within one minute ( Just using it as a bit of fun to see how different computers in the office perform).

Java Code:

class Benchmark {
public static void main(String[] args) {
long endTime = System.currentTimeMillis() + 60000;
int count = 0;
for (int i = 0; System.currentTimeMillis() < endTime; i++) {
double x = Math.sqrt(System.currentTimeMillis());
count = i;
}
System.out.print(count + " calculations per minute");
}
} mh_sh_highlight_all('java');

I am getting results between -2.1billion and -3.4billion which to me would make sense since they are not the best computers in the world but I would be expecting a positive value?

View Replies View Related

JDBC :: Simple Java Program Execution Time Varies All Over The Place

Mar 5, 2012

I've got a very simple java program (J.java, see below) on my application server that successfully connects to an Oracle 11.2 database on a database server (both servers are Linux CentOS) using JDBC thin driver from Oracle.

As you can see from the setURL command in the Java code below, I've configured the application and database servers to sit next to each other, and they're on the same network (cross-cable connected to each other), so there's no network traffic on these (development) boxes except my code.

The problem is the execution time varies a lot. If I run it 5 times, it (seemingly randomly) could take 0.01 seconds, or 10 seconds, or 50 seconds, or over a minute to execute. If it takes over a minute (roughly), the program doesn't complete, but the error shown below is returned instead.

------error returned when execution take more than about 1 minute-------
gf@host9 [~/dbwork]# java -cp ./ojdbc6_g.jar:. J
Exception in thread "main" java.sql.SQLRecoverableException: IO Error: Connection reset
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:494)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:547)

[Code] ....

----------the java code for: J.java-------
// To compile: # javac -cp ./ojdbc6_g.jar:. J.java
// To run: # java -cp ./ojdbc6_g.jar:. J

import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class J {
public static void main(String args[]) throws SQLException {

[Code] ....

View Replies View Related

Catch Arithmetic Exception In Program

Jan 29, 2015

I want to catch the exception in my program is the below way:

class Temp
{
public static void main(String s[])
{
try
{
int x=10/s.length;
System.out.println(x);

[Code] ....

I am expecting my program should give output as "java.lang.ArithmeticException: / by zero" but is giving

Temp.java:11: error: ')' expected
catch (ArithmeticException e | ArrayIndexOutOfBoundsException e)
^
Temp.java:11: error: ';' expected
catch (ArithmeticException e | ArrayIndexOutOfBoundsException e)
^
Temp.java:16: error: 'catch' without 'try'
catch (Exception e)
^
Temp.java:22: error: reached end of file while parsing
}
^
4 error

View Replies View Related







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