Populating Array Doesn't Work Inside Constructor

Feb 24, 2014

Java Code:

import java.io.*;
import java.util.Scanner;
public class asciiFile {
int height;
int width;
Scanner input;
char[][] poop;
public asciiFile(File f) throws FileNotFoundException{ //constructor

[code]...

The constructor is supposed to take an ASCII file, take the numbers in the file, and populate a 2D array with the numbers in the file.

For some reason, the for loop I use to populate the array works outside of the constructor. When I put it in one of the methods, it runs normally. However, when I keep it in the constructor, I get the following error:

Exception in thread "main" java.lang.NullPointerException

at asciiFile.<init>(asciiFile.java:16)

at main.main(main.java:6)

View Replies


ADVERTISEMENT

Why Can't Populate Array Of Objects From Inside Constructor

Feb 21, 2015

The experiments will slowly converge towards one big experiment: a simple game. I have just a little interest in games (perhaps I should have more), but making one - even a simple one - should be self rewarding.

However, now to the point.

* The experiment creates an array of rectangle objects.
* The rectangles are painted inside a Frame object at random x,y coords generated by a random number generator
* The rectangles are stationary.
* The rectangles are each assigned their own random colour.
* The array of rectangle objects is created inside the constructor of the class.

The actual code contains various other variables and methods which would distract from a quick analysis, so below is code which has the same logical structure which also fails (instead of array of rectangles, I have used arrays of integers).

import java.util.Random;
/**
* Experiment 14 - see if it works simply - (with integer arrays)
*/
public class TestingArrays {
// instance variables
int N = 10; // the size of the array - 10 elements
int[] a;

[Code]...

View Replies View Related

Search Form Doesn't Work

Feb 18, 2014

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class frmSearch extends JDialog
{
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
JPanel jpnlMain = new JPanel();

[Code] ....

View Replies View Related

JavaCV Drawing Convexhull Doesn't Work

Sep 9, 2014

import com.googlecode.javacpp.Loader;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.*;
import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
import com.googlecode.javacv.cpp.opencv_core.CvPoint;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSeq;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_highgui.CvCapture;
import com.googlecode.javacv.cpp.opencv_imgproc.CvMoments;

[code]....

Everything works in this except the part where drawing a convexhull and the convexitydefects around an object. Drawing circle around the COG works OK. I tried to draw them with these lines but no luck.

hullSeq = cvConvexHull2(bigContour, hullStorage, CV_COUNTER_CLOCKWISE, 0);

defects = cvConvexityDefects(bigContour, hullSeq, defectsStorage);

cvDrawContours(img1,defects , CvScalar.BLUE, CvScalar.BLUE, 1,0,0);

cvDrawContours(img1,hullSeq , CvScalar.BLUE, CvScalar.BLUE, 1,0,0);

View Replies View Related

KeyListener Doesn't Work - Button Is Not Displayed

Apr 14, 2015

Why the keyTyped function isn't triggered, when i type a key?

Here is my code:

package main;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
 
[Code] .....

I have noticed, that if i call setVisible(true) before i add the button, then it works, but the button is not displayed... How can i achieve that the button is displays AND the KeyListener works?

View Replies View Related

ReadLine Doesn't Work - Cannot Find Symbol

Oct 10, 2014

int arabe = Integer.readLine(args[0]);
String romain= "";

The compilator says that it can't find symbol. The arrow is under the "".""

It worked before.

View Replies View Related

HTTP KeepAlive Seems Doesn't Work With Java

Jun 10, 2015

I have java http client which sends periodically (every 30 sec; this code is run by heartbeat thread in the cycle) heartbeats:
 
private PostResponse post(String jSessionCookie, final String action, final String data, final int postTimeoutMs) throws IOException, SSYSException
{          
final HttpURLConnection httpConn = openHttpUrlConnection(true, postTimeoutMs, jSessionCookie);
final OutputStream os = httpConn.getOutputStream();
try (final PrintWriter wr = new PrintWriter( DefaultProperty.isEnableSocketTraceGW ? new TracerOutputStream(os) : os ))

[Code] .....
 
On the server side there is Tomcat 8.0.21 + APR connector. Every time this heartbeat is sent I see in the Wireshark and EtherDetect that new TCP connection is opened (SYN-SYNACK packets) and after getting response from Tomcat connection is closed (FIN – FINACK packets). I was expecting that TCP connections will be reused but not closed.

Capture.png 182.0 K

View Replies View Related

Works In Netbeans / Eclipse But Doesn't Work After Being Compiled By Either

Mar 2, 2014

There is a specific function I have added to a program I've been working with for a while which involves retrieving data from a website. Here is that code:

Java Code: public String getWebData(String urlString, String add) throws IOException{
String output = "";
try {
//+s being the token, for example if dictionary.com was being used
add = add.replace(" ", "+s");
urlString = urlString + add;
URL url = new URL(urlString);
InputStream inputStream = url.openStream();

[code]....

Anyway, when I run this program within Netbeans, it works perfectly. I have a backup of the project in eclipse as well, and I've copied all of the code over and tried running the same thing in Eclipse - exactly the same, it works perfectly. The problem is whether I compile the the code in Netbeans or Eclipse, the exported runnable jar for some reason has an issue with this one method. It doesn't crash, and it seems to be doing something, but it is by no means giving me the data from the website like it is supposed to.

View Replies View Related

Code That Works On Fiddle But Doesn't Work On Local

Oct 9, 2014

I have this code: [URL] .... It works on fiddle but on local it does not work. What should be the problem?

Fiddle:

$('#addnewline').on('click', function (e) {
e.preventDefault();
var $textarea = $('#thetext');
$textarea.val(function () {
return $(this).val().substring(0, this.selectionstart) + "<br>" + $(this).val().substring(this.selectionstart);
});
});
<button id="addnewline">New line</button>
<br />
<textarea rows="4" cols="50" id="thetext">Some text

View Replies View Related

JSP :: Searching Data Using NON English Language Words Doesn't Work

Oct 30, 2014

Below is my code

<%--
Document : closeAc
--%>
<%@page import="javax.swing.JOptionPane"%>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.sql.*, java.util.Date;"%>
<%
try {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

[code]....

All I'm trying to do is to search the data from the database and is doesn't show up!

View Replies View Related

Read XML File And Delete Its Contents - Boolean Doesn't Appear To Work

Oct 17, 2014

I'm trying to read a xml file and delete it's contents. I do this by reading the file,writing it to a temp and then overwriting the original with the temp by renaming it

//overwrite original xml file with new file
boolean successful = outputFile.renameTo(inputFile);
System.out.println("success");

It does say the value of the local variable is not used however. I've debugged to ensure it hits the code it always prints out the line after too.It just does not overwrite my original xml file with the temp one.

It's had votes on stack so I thought that would of been reputableStack - overwrite but the second one got voted as a good answer. But still I would like to know if my code can work or not.

View Replies View Related

Swing/AWT/SWT :: MouseListener Doesn't Work If JList Has Custom CellRenderer

Nov 9, 2014

I have a JList<Object> in my code (it actually takes JLabels) called imageList, and I've given it a custom CellRenderer using the following code:

cellRenderer = new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {

[Code] .....

However, when I click anywhere on the JList, nothing gets printed to the console, which suggests that the mousePressed() method isn't being invoked. I think it's a problem with the CellRenderer, because I have similar code elsewhere that works, the only difference being I don't use a custom CellRenderer.

View Replies View Related

Simple If Statement Taking A String Input Doesn't Work

Jun 6, 2014

Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input == "next") {
System.out.print("good Job!");
}
else {
System.out.println("Why ?");
}

//If I type in next it prints out "Why ?" instead of "Good Job!" - Why though ?

View Replies View Related

Servlets :: Setting Httponly Programmatically In Cookies Doesn't Seem To Work

Nov 5, 2014

I am using servlet 2.4 I used the ff. code below to set httponly in my application's cookies but it did not work. When I do a javascrip alert (document. cooke) in my page, the session id still shows up.

Cookie [] cookies = request.getCookies();
for(int x=0; x<cookies.length; x++){
Cookie cookie = (Cookie) cookies[x];
String cookieValue = cookie.getValue();
cookie.setValue(cookieValue + "; HttpOnly");
}

I also tried doing this and it wouldn't work too

String sessionid = request.getSession().getId();
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");

by the way I am using an application server with its JAVA EE version = 1.4 and JAVA SE version = 5

View Replies View Related

If Statement Won't Work Inside A While Loop

Dec 12, 2014

I made this calculator in C++ and it worked wonderful so I decided to make it in java. When I run the program it gives me no errors but my if statements inside my while loop don't work

import java.util.Scanner;
public class ohmlaw {
public static void main(String args[]) {
float current;
float resistance;
float voltage;
String calchoice = new String();
Scanner cc = new Scanner(System.in);

[code]....

View Replies View Related

Polymorphic Method Inside Constructor

Aug 1, 2014

Why in this code testSon class void display() method is called instead of testFather class void display()

class testFather
{
void display() {
System.out.println("This is testFather class");
}
testFather() //testFather constructor {
display();

[Code] .....

Output : This is testSon class /* why not This is testFather class*/
This is cons of testSon class

View Replies View Related

Java - Populating Terms Array?

Mar 18, 2015

I must convert some Java fubction to a plain "Basic", as VB6. The problem I'm facing is this: Suppose I have an array like

Java Code:

private static final int[][] Terms = {
{193, 26, 13},
{183, 29, 14},
{170, 20, 11}
}; // total 659 terms mh_sh_highlight_all('java');

How do I populate the Terms array?

Is it:

Terms[0,0]=193;
Terms[1,0]=26;
Terms[2,0]=13;
Terms[0,1]=183;
Terms[1,1]=29;
Terms[2,1]=14;
Terms[0,2]=170;
Terms[1,2]=20;
Terms[2,2]=11;

?

I'm not sure this is right... Is there a way to automate this process? What if we have arrays like int[][][] Terms? This is terrible... Is there a software tool for this?

View Replies View Related

Array Doesn't Change From Default Entries

Dec 7, 2014

I have a 2d array that i am manipulating. In my class i have a constructor that takes the dimensions of the array and within th econstructor i need to randomly fill the array. However, when i try to manipulate it in the test program, all that prints out are the default values.

here is the class

import java.util.*;
import java.lang.Math;
import java.util.Arrays;
import java.util.Random;
class SummerStats

[Code] .....

And here is the printout

Enter number of rows(people):
3
Enter number of columns(years):
3
Enter number of person to find sum salary:
1
Enter year to find Max salary of that year:
1
[]
[]
The max salary is at index: (0, 0, )
The largest salary ocurred in year: 0
The sum of person 1 is: 0.0
The total of all salaries is: $0.0
The max salary in year 1 is: 0.0
The average salaries for each year:
0.0, 0.0, 0.0,

The total salary for each person is recorded below.

And the last method called doesn't finish or printout ie the program doesnt end

View Replies View Related

How To Get String Array To Work With Int Array

Feb 9, 2015

I have to create an inventory program that displays a product number, name of product, number of units in stock, price of each unit, and then at the end total up the entire value of the inventory. I am a beginner as I am 5 weeks into my first programmer class and I do want to learn how to program. I am able to get the inventory array with the (int) to display in the columns but I do not know how to get the String array with the DVD's to display where they are suppose to. I also cannot figure out how to calculate the quantity with the price to give me an overall total.

This is my code so far:

public class Product // begin Product class
{
int Stock[] = { 101, 102, 103, 104, 105 };
String[] DVD = new String[5];
double Price[] = { 10.00, 10.00, 12.50, 18.50, 11.50 };
int Quantity[] = { 1, 5, 4, 3, 4 };

[Code] .....

View Replies View Related

Creating Array Of Objects In Constructor

Mar 16, 2014

I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.

I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.

here is my contacts class

public class Contact
{
String name;
int number;

[Code].....

In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?

View Replies View Related

Randomly Fill 2D Array In Constructor

Dec 7, 2014

I must fill a 2d array randomly and then apply methods to the array. However i keep getting an out of bounds exception no matter what dimensions i use. I have a test and a class program.

import java.util.*;
import java.lang.Math;
import java.util.Arrays;
import java.util.Random;
class SummerStats {
Random rand = new Random();

[Code] .....

View Replies View Related

Array List - Not Suitable Constructor For LineItem

Apr 19, 2014

I am working in NetBeans and I am receiving numerous error messages with my code "not suitable constructor for lineItem.

import java.util.ArrayList;
public class Transaction {
private final ArrayList<LineItem> lineItems;
private int customerID;
private String customerName;
private String LineItem;
private int i;

[Code] .....

Specific Requirements for the Transaction Class :

1. The Transaction class should have a constructor with two parameters. The first is an integer containing the customer's ID and the second is a String containing the customer's name.

2. There should be a method to allow the addition of a line item to the transcript. The three parameters for the addLineItem method will be (1) the item name, (2) the quantity, and (3) the single item price.

3. There should be a method to allow the updating of a line item already in the transaction. Notice that updating an item means changing the quantity or price (or both). The parameters for the updateItem method are also (1) the item name, (2) the quantity, and (3) the single item price.

Notice that the updating of a specific line item requires a search through the ArrayList to find the desired item. Anytime a search is done, the possibility exists that the search will be unsuccessful. It is often difficult to decide what action should be taken when such an "exception" occurs. Since exception handling is not covered until later in this textbook, make some arbitrary decisions for this project. If the item to be updated is not found, take the simplest action possible and do nothing. Do not print an error message to the screen. Simply leave the transaction unchanged.

4. The transaction class needs a method called getTotalPrice to return the total price of the transaction.

5. There should also be a method to return information about a specific line item. It should return a single String object in the same format described for the LineItem class:

Colgate Toothpaste qty 2 @ $2.99 $5.98

Again, the possibility exists that the search for a specific line item will fail. In this instance, you should return a string containing a message similar to this:

Colgate Toothpaste not found.

6. The final method needed is a toString method. It should return the transaction information in a single String object. It should use the following format:

Customer ID : 12345
Customer Name : John Doe

Colgate Toothpaste qty 2 @ $2.99 $5.98
Bounty Paper Towels qty 1 @ $1.49 $1.49
Kleenex Tissue qty 1 @ $2.49 $2.49

Transaction Total $9.96

View Replies View Related

Placing Numbers Inside Array

Apr 3, 2015

"on each step of the loop you can calculate an entire year as opposed to a single month, otherwise you can calculate monthly, but instead of printing, create an array and fill it up with your solutions, then have a second loop where you add them up by dozens to print yearly values, alternatively, have a counter k that adds up to 12, and two variables for adding up the monthly results, increment these after you calculate the monthly value, and whenever k hits 12, print them and reset to zero. print a final time once you leave the loop. "

int year = loanDurationYears-14;
int[] years= new int[loanDurationYears];
periods = loanDurationYears*12;
for(int i=0;i<1;i++)
{
for(year = 0;year<loanDurationYears;year++)
{
years[year] = year+1;
 
 [code]....

View Replies View Related

Constructor That Creates A New Object With Data From Array Values?

Feb 11, 2015

So I want to write a constructor that creates a new object with the data from the array values. I don't know where to start. It's the last method in the code:

public class Measurements {
private double[] values;
private double[] newArray;
private int n; //numberofvalues
private double[] ms;
public Measurements(int max) { //constructor

[code]....

View Replies View Related

Null Detected In String Array Not Saved By Class Constructor

Mar 12, 2014

I've a vertical-bar-delimited file where most elements contain text, some contain whitespace, and some are empty. Examples:

62RG|fe|Pencil Financial Group, LLC||doug@pencil.com|||85637889|Cross, Ben|bcross@godaddy.net|Bernard|Cross|Ben||315 One Tree Hill Terrace|Lafayette|LA

62RG|fe|Pencil Financial Group, LLC||tracy@pencil.com|||13658734|Dustin Cardwright|dcart@motorola.com|Dustin|Cartwright|||| |LA

which I parse and store with

String str_arry = innline.split( "|", 17);
lisst.add( new Contact( str_arry));

and my Contact class has the constructor

public Contact( String[] str_arry) {
for( int ii = 0 ; ii < str_arry.length ; ii++ ) {
if( str_arry[ii].matches("^s+$")) {
str_arry[ii] = null;
System.out.println("hit a null");

[Code]...

I expect the for-loop in the constructor to find any elements containing whitespace characters and set them to null for subsequent assignment.And when the code runs I do see some hit-statements pop up, so the detecting part is working.

But when I then process the list and access a Contact object and test fields for nulls I don't find any ie

if( aContactObj.getfFCity() == null) System.out.println("city is null");

never prints when it should.

What's the trick? Or is my approach wrong and if so what should it be?

View Replies View Related

Reading Entire Integer Text File And Putting Inside Array?

Apr 5, 2014

I have an assignment on sorting, i kno i can get the sorting down but im having an issue with inputing the 512 ints in a file into an array. the instructor provided us with a file with 4 equal sets of ints. i tried to make my array of size [scan.nextInt()] and it cuts off the last 21 ints. and skips the first int. how can i get all of the integers in the text file into my array? this is what i have so far. if i hard code the array to size 50000 and then try to print the array it compiles but errors out when running it.

System.out.println("Please Enter text file in this format, XXXXX.txt :");
String file =fileName.nextLine();
Scanner scan = new Scanner(new File(file));
int [] data = new int[scan.nextInt()]; <-------here it skips first int
int count= data.length;
for (int i=0; i<data.length-1;i++) {
data[i]=scan.nextInt();
}
System.out.print(Arrays.toString(data));

rst 4 ints in output are: 501, 257, 390, 478...., supposed to be 492,501,390....and last ints are: ....88, 83, 79, 0 and supposed to be :88 83 79 77 76 72 71 71 66 57 56 48 48 41 33 30 23 23 18 17 15 13 9....it replace last ints with 0. why ? and how do i fix this. attached it the text file

View Replies View Related







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