BestJewSinceJC 700 Posting Maven

You could try serializing the JPanel class and seeing if that works as wanted when you load it. I have no idea if that will work or not for an image the user drew on the panel though, but it might be worth your time to try it out since Serializing something doesn't take very long.

BestJewSinceJC 700 Posting Maven

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op2.html

Read the section on instanceof. One good use of instanceof is in the equals() method that is inherited from the Object class. Since the method is defined as taking a type Object as a parameter, you need to check that it is of the correct type before casting it to that type - otherwise you would get an error. Read this article for info about how to implement the equals() method if you never have before. In their implementation of the equals method, you'll see that they use instanceof.

BestJewSinceJC 700 Posting Maven

There are alternatives but ArrayList is probably the easiest type of collection you can use. ArrayList isn't an array, but it uses an array in the underlying implementation. An array is just a chunk of contiguous memory that can hold things; an ArrayList is a java Object. The ArrayList class offers up methods that allow the user easy access to elements held in the underlying array. For example you could do stuff like the following:

ArrayList<String> list = new ArrayList<String>();
list.add("WOOHOO");
if ("WOOHOO".equals(list.get(0)) System.out.println("They're the same");

So you see it is pretty simple to add stuff to an ArrayList and get stuff back out of it.

Anyway, that being said you do not have to use an ArrayList to solve this problem. I was just offering it up as one way to do it. Taking your original code, check out my edits:

import java.util.Scanner;

public class Main
{
        public static void main(String[]args)
        {
              Scanner Scan = new Scanner(System.in);
      
              int charCount = 0;
	      int numWords = 0;
 
	      System.out.println("\n\nThis program asks you to type in a sentence,");
	      System.out.println("it then requires a single letter of the alphabet");
              System.out.println("to be entered in and displays the number of words");
	      System.out.println("as well as the total number of occurrences.");
			 
              System.out.print("Enter a sentence: ");
              String userString = Scan.nextLine();

              System.out.print("Enter a letter: ");
              char userChar = Scan.nextLine().charAt(0);


              userString = userString.substring(0, userString.length()-1);
              for (int i = 0; i < userString.length(); i++)
              {
                                    if (userString.charAt(i) == userChar)
                                    {
                                    charCount++;
                                    }

              }

Scanner countWords = new Scanner(userString);
int wordsWithTheLetter …
BestJewSinceJC 700 Posting Maven

I think you might be trying to add your entire ArrayList into the JList, which would be a mistake. You can do something like this:

ArrayList<Location> physicalWatchList = new ArrayList<Location>();
// .. some code to add Locations to the physicalWatchList goes here
DefaultListModel model = new DefaultListModel();
for (Location loc: physicalWatchList) model.addElement(loc.toString());
JList list = new JList(model);

//Some time later when you want to add more elements
list.getModel().addElement(newLocation.toString());

Also, make sure your Location class actually overrides the toString method from the Object class otherwise it is not going to output what you might want it to.

BestJewSinceJC 700 Posting Maven
return (tr.setPrice() + tp.setPrice() + tq.setPrice());

If you look in your BillPanel class, you never initialized any of those variables. Therefore, there contents are null, and you are getting a NullPointerException. How do you expect to say tr.setPrice() when you never created "tr"? Essentially tr at that point is just an empty variable with nothing in it. You have to say tr = new PizzaPanel() at some point in your code before you try to use the variable tr. The same goes for all of your other variables.

BestJewSinceJC 700 Posting Maven

I accidentally left the prompt out in the snippet I gave you. Obviously you need to prompt the user for input and allow them to enter some input, otherwise it will not run correctly. Oh, and you could also add each word that they input to an ArrayList. Then use a for loop on each word in the ArrayList to count the letters.

BestJewSinceJC 700 Posting Maven

Probably because every time someone clicked it, it tried to check every member to see who had that many posts. It'd seem more reasonable to calculate that figure once per week (during a time when the server has a low load like late at night) and to keep a file of the list of members who fit the category. I don't know very much about DB load so that is just a thought, it might be totally off.

BestJewSinceJC 700 Posting Maven

Can someone please close this thread? For the last week I've been hoping it would die, but it seems like every couple days somebody posts a new "solution" in here.

BestJewSinceJC 700 Posting Maven

Your output isn't correct because you are only checking to see how many words exist in your input, not how many words have the letter you are looking for. You might want to do something like

Scanner input = new Scanner(System.in);
int wordsWithTheLetter = 0;
while(input.hasNext()){
String word = input.next();
for (int i = 0; i < word.length(); i++){
if (word.charAt(i) == yourChar){
wordsWithTheLetter++;
break;
}
}
}

Usually I wouldn't give this much code, but in your case it looks like you've already put forth a lot of effort and you aren't very far from a solution. I'll leave integrating that example into your code up to you. Keep in mind it isn't the only way to solve your problem, and your approach of trying to do both at once (count words and count characters) is slightly more efficient. But in this case I'd trade efficiency for clarity as it is easier to write two separate pieces of code.

BestJewSinceJC 700 Posting Maven

Are you sure you aren't missing a . right before the second ?
I just did something similar in Perl so I can probably help.. but an example of what your input and output are would be nice.

BestJewSinceJC 700 Posting Maven

character[0] wasn't initialized . . that's all I can tell you from the information given.

BestJewSinceJC 700 Posting Maven

The jist of it is to say new Date(year, month, day) and to make sure that year, month, and day all conform to the guidelines in the documentation.

BestJewSinceJC 700 Posting Maven

David, I think this example might help. Note that you should still check out the link Ezzaral selected; I only implemented one of three methods that it suggested to implement.

public class Person {
	String ssn = "";
	String firstName = "";
	String lastName = "";
	
	
	public Person(String ssn, String first, String last){
		this.ssn = ssn;
		this.firstName = first;
		this.lastName = last;
	}
}
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class JListExample extends AbstractListModel {
	ArrayList<Person> list = new ArrayList<Person>();
	
	@Override
	public Object getElementAt(int arg0) {
		return list.get(arg0).lastName;
	}

	@Override
	public int getSize() {
		return list.size();
	}
	
	public void addPerson(Person p){
		list.add(p);
		fireContentsChanged(this, list.size()-1, list.size()-1);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame jListDisplay = new JFrame();
		JPanel listPanel = new JPanel();
		final JListExample exampleList = new JListExample();
		exampleList.addPerson(new Person("217-25-2525", "Kyle", "InventedName")); //SSN isn't real, !!
		JList list = new JList(exampleList);
		jListDisplay.add(listPanel);
		listPanel.add(list);
		jListDisplay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JButton addPerson = new JButton("Add person");
		final JTextField field = new JTextField("Enter last name");
		addPerson.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				String lastName = field.getText();
				exampleList.addPerson(new Person("blankSSN", "Ken", lastName));
			}
			
		});
		
		listPanel.add(field);
		listPanel.add(addPerson);
		jListDisplay.setPreferredSize(new Dimension(300,300));
		jListDisplay.pack();
		jListDisplay.setVisible(true);
	}

}

I hope that helps. The Person class is obviously just a little helper class. Neither class that I posted is completely implemented, but I think it demonstrates the basic concept of how to extend and implement the AbstractListModel class …

BestJewSinceJC 700 Posting Maven

Hey, Sean. Good to have you here. So what languages do you like? What are you interests as far as programming? Desktop or web oriented?

BestJewSinceJC 700 Posting Maven

You might also agree with him if he says 1 + 1 = 3 but that doesn't make it any more true.

BestJewSinceJC 700 Posting Maven

You told us this is a desktop application. What is a form? Just tell us what type of Objects you are using for your window... otherwise how are we supposed to help you?

BestJewSinceJC 700 Posting Maven

Well your switch statement has no affect because you declared your variables inside the switch. Declare the variables outside of the switch if you want your assignment statements to do anything. i.e. what I did with your 'm' variable below.

public class Travel {
   
   public static void main(String[] argv) 
   {
    
        double traveldistance, time, m;
        int convertseconds, hours, remainder, minutes, seconds;
        
        char roadtype;
                      
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        System.out.println ("Type the road type:");     // Prompts to enter travel distance and reads the values
        roadtype = UserInput.readChar();
                         
        switch (roadtype){
            case 'm':                                    // Motorway
                     m=85;
                     break;
                    
            case 'a':                                   // A Road
                     double a=70;
                     break;
                    
            case 'b':                                   // B Road
                     double b=55;
                     break;
                    
            case 'u':                                   // Urban Road
                     double u=40;
                     break;
            
            default:
                    System.out.println("Invalid road type " + roadtype);          // Invalid road type
                    System.exit(0);
                    break;
        }
                
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        System.out.println ("Type the travel distance:");    // Prompts to enter travel distance and reads the values
        traveldistance = UserInput.readDouble();
                      
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
   
        time = traveldistance / roadtype;            // formula (units in hours)
        
        convertseconds = (int)((time * 60) * 60);    // converts hours to seconds
                        
        hours = convertseconds / 3600;               // converts the seconds to HH:MM:SS
        remainder = convertseconds % 3600;
        minutes = remainder / 60;
        seconds = remainder % 60;
        
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        System.out.println ("To travel " + traveldistance + " takes " + convertseconds + " seconds");
        System.out.println ("To travel " + traveldistance + " takes " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
              
   
   } // end of main

} // end class
BestJewSinceJC 700 Posting Maven

Will I would love to have $600 USD after bills are paid,but let's not squabble about personal life.so back to original subject? Later---

Why not talk about personal life? I never understood why just because it's online people think they can't say anything personal at all. There are limits, of course, but why would you care what anyone has to say if you know nothing about them? (This is more a random thought that you prompted than something directed at you.. lol)

Anyway, he didn't say what was included in his "600 USD" so he probably has to buy groceries with that, etc. And the original topic of this thread is pretty much toast. You shared your feelings on it, and most everyone agrees that the ad is intrusive - there isn't much more to talk about.

BestJewSinceJC 700 Posting Maven

Code snippets should be posted for working code, post a regular thread for questions in the future.

BestJewSinceJC 700 Posting Maven

What does T___T mean?

BestJewSinceJC 700 Posting Maven

Tell you what you pay my $45 until job cranks back up to full time check. Then I will pay full freight. Anyhoo back in real life I'll make my self as useful as possible, because feel good doesn't pay for roof & family. Not grumping just stating facts. Later---

Yeah but for some of these guys in here, $45 is probably only a little over an hour of work. Hardly breaking the bank.

BestJewSinceJC 700 Posting Maven

There is a general set of rules for the site and numerous announcements telling you how to post in this forum. Any one of those things would have clarified that we don't write people's homework. I'll even link you to them.

http://www.daniweb.com/forums/announcement9-2.html
http://www.daniweb.com/forums/faq.php?faq=daniweb_policies

BestJewSinceJC 700 Posting Maven

It means that, at the line where you got that error, you are trying to use a variable which has not been initialized.

BestJewSinceJC 700 Posting Maven

Try adding a leading "/" in the call to getResource()

BestJewSinceJC 700 Posting Maven

@ OP:

You're using the Date class constructor incorrectly. It says to put the arguments in as year, month, day. Furthermore if you read the Javadoc for the Date class's constructor you are using you will see that even if you reorder your parameters, it still won't work as expected. Month according to the description must be between 0-11. Oh, and the method also says that it is deprecated - i.e. its use is discouraged and it is only really there so that older programs do not break.


http://www.java-forums.org/java-util/7176-how-compare-two-dates.html

BestJewSinceJC 700 Posting Maven

That article is kind of amusing; everyone graciously refraining from taking credit except for the marketing woman who is obviously lying since three other accounts contradict her story.

BestJewSinceJC 700 Posting Maven

How would that reduce the problem? Now if there was a fee for each post :) :) :) But that would probably eliminate everything in Geeks' Lounge, except for those members who have too much money.

I'm envisioning a new Geek's lounge now: Dani makes a post, dani pays herself for said post, dani makes a post, dani pays herself for said post...

BestJewSinceJC 700 Posting Maven

Or perhaps most people don't care that google has mundane information about them on their databases. .

BestJewSinceJC 700 Posting Maven

http://java.sun.com/docs/books/tutorial/uiswing/components/button.html

They have fully working examples as well as explanations. If you go to some of the JButton examples you'll be able to adapt it to your needs. You also might want to check out some other Swing topics such as how to use GridLayout (also has examples with JButtons)

BestJewSinceJC 700 Posting Maven

Another note: I actually had to play around a lot to get all of this to work. It took me maybe 30 minutes. I wasn't able to use getResource() to read a text file at all. If anyone else has any examples of using getResource (rather than getResourceAsStream which I ended up using), that would be helpful. It doesn't really matter what you use as long as it works, but I'm just curious how it would be done. The first link I posted in my first post in this thread claims that using getResourceAsStream is much easier, which is why I switched to that (besides, I could create a Scanner from it directly, given the fact that it returns an InputStream).

BestJewSinceJC 700 Posting Maven

Yes. In your "main package" you can add a folder called resources. In that resources folder you can put your files. Then you can export the project as a Runnable Jar File in eclipse by going to File->Export->(Choose Java Option)->Runnable Jar File. Here is a code sample to get you started. Keep in mind that the way I told you to add the folder and the location of that folder are *not* the only way to do it, but it is one way. You can experiment on your own to see other ways or you can read this article on accessing resources and this article on the various ways you can arrange resources in your jar files (go down to the section on loading images using getResource). Keep in mind that the code sample I provided below uses a file called test2.txt which is in a folder called resources. And if you run this on a long text file you'll be in for a surprise because JOptionPanes will probably keep popping up because of the while loop at the end.

import java.io.InputStream;
import java.util.Scanner;

import javax.swing.JOptionPane;


public class ResourceTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InputStream stream = ResourceTest.class.getResourceAsStream("/resources/test2.txt");
		if (stream == null) JOptionPane.showMessageDialog(null, "Resource not located.");

		Scanner input = null;
		try {
		 input = new Scanner (stream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "Scanner error");
		}
		
		while (input.hasNextLine()) JOptionPane.showMessageDialog(null, input.nextLine());
	}
	
}
BestJewSinceJC 700 Posting Maven
BestJewSinceJC 700 Posting Maven

Call the setDefaultCloseOperation method on your JFrame.

BestJewSinceJC 700 Posting Maven

edit: Sorry for the freepost, I was confused there for a second by the similarity of the previous poster's reply to my first reply.

Anyway, you don't need to create a third list, and really you can do it with either LinkedList or ArrayList since they both extend List. The Collections.sort method is defined as taking a List as its parameter.

BestJewSinceJC 700 Posting Maven

User agreements are notoriously long and dry. . :(

BestJewSinceJC 700 Posting Maven

As the documentation that I linked you to previously states,

All elements in the list must implement the Comparable interface

So make your class implement Comparable, then write the compareTo method. Here is how to write compareTo.

I can't emphasize enough that it is important to learn how to use the Javadoc documentation. I'm happy to help you as much as you need it, but to become an independent programmer, it is important to be able to read it.

BestJewSinceJC 700 Posting Maven

Add one to the other using a for loop or a for-each loop.
Use Collections.sort(linkedList) to sort it.

BestJewSinceJC 700 Posting Maven
Collections.sort(yourArrayList);

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List%29

And mark your other thread solved, since you're apparently finished with it.

BestJewSinceJC 700 Posting Maven

list.remove(index) will make it shrink list.add(element) will make it grow. Go look at the ArrayList Javadoc; it shows you how to use the ArrayList class

http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html

BestJewSinceJC 700 Posting Maven

Ok,

int[] array = new int[10];
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i: array){
list.add(i);
}
BestJewSinceJC 700 Posting Maven

My suggestion is much easier so whether or not it is a homework assignment is irrelevant. It isn't a contest, I'm just giving the OP what I think is a better solution.

BestJewSinceJC 700 Posting Maven

Nevermind, I was assuming you had a school assignment. Using ArrayList is perfectly fine. You should know the concepts behind an array though (ArrayList uses an underlying array, and arrays are very important in computer science).

BestJewSinceJC 700 Posting Maven

If your teacher requires that you make your own get, remove, etc, then there is a good chance your teacher also requires that you use your own array - not ArrayList. That being said, if you really want to have your own get method, you could do

public Car get(int index){
return arrayList.get(index);
}

You can figure out the other methods, they are basically identical. Use the ArrayList documentation. But again, what you're doing sounds like a bad idea to me.

BestJewSinceJC 700 Posting Maven

Hmmm ok and how do i use the try catch method? and where do i throw it to?

try{
int number = Integer.parseInt("Some string here");
if (number > 0) // YAY!
else //BOO!
}catch(Exception e){
//WTH! Problem!
}

And instead of doing whatever gangsta is pointing you towards, just use an if statement, lol.

BestJewSinceJC 700 Posting Maven

Follow the rules and post a question and show effort.

BestJewSinceJC 700 Posting Maven

Do you mean a JFormattedTextField? And you'd do something like

Integer.parseInt(textField.getValue());

Keep in mind that you should use a try catch in case of input error. Double has a similar method if you want to parse a double.

BestJewSinceJC 700 Posting Maven

Code snippets are for working code examples, not for getting help. Normal threads with your code in code tags are for help.

BestJewSinceJC 700 Posting Maven

private - only access it in methods of the same class. If you don't like this but want to keep it private, either use get and set methods or you're out of luck.

BestJewSinceJC 700 Posting Maven

Use code tags.

BestJewSinceJC 700 Posting Maven

And just as a nitpicky point that I didn't mention before, you can definitely run a program that requires command line arguments without using the command line. For example, I can run it in Eclipse and just supply the command line arguments.