JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Looks l;ike a very interesting bug starting with ballGame = new BallGame(); in main.

First, new BallGame() is called. That constructor calls Renderer.repaint() which executes BallGame.ballGame.Repaint(g); then, and only then, after the constructor has returned, the variable ballGame is set to refer to the new BallGame.

So when you execute BallGame.ballGame.Repaint(g);, ballGameis still null and you get an NPE

ps You still need a Timer, not a loop!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It seems there's a problem where Google has been failing to give enough prominence to sites like DaniWeb when people search for IT help, so please tell all your friends about us and give us some good exposure in your social media. We're still here and ready to help.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

We are here to help people who are trying to work hard and learn. We are not here to do Google searches for people who may be too lazy or too stupid to do their own searches before asking a question.
Correct your attitude and try again.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's called a "bubble sort" - just Google for details.

Apart from tjhat it just copies a List of students into an array so the sort will be fast, sorts the array, then copies the sorted reults back into the list. That part of the code should work, but it's not as good as it could be.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's what you get if the text field does not contain a correctly formatted decimal number ie it must contain exactly one decimal point and at least one digit and nothing else. This is a problem if you are using French formatting as in your original post.
You can do some simple processing on the user input to make it compatible using String's replace method. I'll let you work out the details of the code, but here are the steps:

get the text from the field into a string
replace all the blanks with nothing, eg s= s.replace(" ", "");
replace all the "." with nothing (thousands separators are not supported)
replace the comma decimal point with a full stop (English standard)

NB If you are using a French locale then you may not need to change the decimal point - try it and see.

When this works then put it in a little method so you can just call that for each text field

Finally, you should catch that exception in your code because it will always be triggered if the user types incorrect input (eg O instead of 0). You should catch it, issue a sensible error message to the user and wait for new input.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Thats 100% pure standard Java SE.
It uses Streams, lambdas, and method references, all introduced with Java 8 in spring 2014.
Most Java courses are still waiting to be updated to relflect current Java, so your teacher may not be familiar with them.
Within the Java community the are considered to be very important extension to the original language.

It also uses the concept of a "fluent" API so you can chain calls together for greater readability. It's not a change to the language syntax, just a convention about how you define methods.

I can explain any of these in more detail if you're interested.
JC

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Ah yes, APL. In 1970 I was given my own APL golfball for coding on a 16kB IBM 1130 computer. I used it to write an assembler for an IBM System 7 process control computer (we were developing software for it pre-release and coudn't wait for the labs to ship a proper working assembler). Oh what fun we had in those heady early days.
It was, and maybe still is, the world's first WOL - "write only language" - a reference to the fact that you coudn't read it.

rproffitt commented: Maybe WOL is better than ROL (read only language.) +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Well.... yes.

It was inspired by the Ruby each_slice(5) thing that pty posted. It looked like a neat and useful thing that Java doesn't have. So I started out trying to do a Java version. The print-oriented version was a step on the road, but since then I have got it a lot more generic and closer to the original.
Now I have a "slicer" Collector that breaks a Stream<T> into substreams of a given size ie a Stream<Stream<T>>
You can do lots of things with that, including printing stuff in comma-delimited blocks of 5, ie

(some stream)
.collect(new SlicerBuilder(5).build())
.map(s -> s.collect(Collectors.joining(", "))) 
.forEach(System.out::println);

.collect(new SlicerBuilder(5).build()) 
// break into substreams of length 5

.map(s -> s.collect(Collectors.joining(", "))) 
// convert each substream to a comma-delimited list

.forEach(System.out::println);
// print each comma-delimited list on a new line

The code for the builder is a bit longer :), but it's just a utility thing that can be re-used endlessly. It would also be pretty trivial to adapt or extend it to split a stream on any other criteria

    class SlicerBuilder {

         private final int itemsPerGroup; 

        public SlicerBuilder(int itemsPerGroup) {
            this.itemsPerGroup = itemsPerGroup;
        }

        public <T> Collector<T, ?, Stream<Stream<T>>> build() {
            ArrayList<T> temp = new ArrayList<>();
            return Collector.of(
                    () -> new ArrayList<Stream<T>>(),
                    (list, i) -> {
                        temp.add(i);
                        if (temp.size() >= itemsPerGroup) {
                            list.add(new ArrayList(temp).stream());
                            temp.clear();
                        }
                    },
                    (list1, list2) -> {
                        list1.addAll(list2);
                        return list1;
                    },
                    list -> {
                        if (!temp.isEmpty()) list.add(temp.stream());
                        return list.stream();
                    }
            );
        }

    }
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I haven't been able to come up with a really elegant way to print 5 values per line...

OK, a bit off-topic, but I wanted to share this with anyone who may have been interested...
The problem is to print a Stream of numbers formatted at 5 per line.
I tackled this by creating a Collector that takes a Stream of Objects and returns a Stream of Strings in groups with different separators within groups and between groups, and threw in a formatting option for the Objects themselves.
In good Java 8 style I wrote a fluent builder to create Collectors with any or all of those options.
In use it looks like this

// adds a new line before each new group of 5

  (some arbitrary Stream)
. collect(new GrouperBuilder(5).groupPrefix("\n").build())
. forEach(System.out::print);

// build example with all the options
new GrouperBuilder(3) // 3 items per group
.prefix(", ")         // commas between them
.groupPrefix("\n")    // new lines between groups
.format("%4d")        // format items as 4 col ints
.build()              // create the Collector

// creates output like
//  24,   36,   48
//  60,   72,   84
//  96

and here (if anyone cares) is the builder code. Please comment and suggest improvements...

  class GrouperBuilder {

        // converts stream of Objects to stream of fornated Strings in groups

        private final int itemsPerGroup; // number of items in each group. Mandatory

        // optional formatting values...
        private String prefix = "";      // text to put between items within …
Reverend Jim commented: Kewl +15
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No worries - "praise where praise is due"
If I were to write that the only changes I would make would be:
1) Some kind of very simple validation on the user input so it crashes out of bad input with a friendly error message
and
2) instead of i < secondNumber + 1 I would write i <= secondNumber

(or, for fun, I would write it using Streams range and filter as in my earlier post)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, I'd say beautiful.
The equivalent in Java is quite pretty too...

int lower = 16, upper = 99;

IntStream.rangeClosed(lower,upper)
   .filter(i -> i%3 == 0 && i%4 == 0)
   .forEach(System.out::print);

,,, but I haven't been able to come up with a really elegant way to print 5 values per line - any ideas anyone?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The C++11 Standard says that signed integer overflow/underflow behaviour is "undefined", so any compiler can legally do whatever it wants, including ignore it. Ignoring it (on normal computers) is a lot easier and faster that detecting it and doing something sensible. That's C++ for you.

8.4: If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sam:
You have not asked a sensible question. We have no idea of what you already know or what help you need. Please read the link RJ gave you and then try again. We do help people, but only those who show some effort and ask answerable questions.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Half of the U.S. population reads a newspaper. Half of the U.S. population votes. Let’s hope it is the same half.

Ironic. Half the UK population reads the Daily Mail (1), half voted in the Brexit election. Unfortunately they were the same half.

(1) not actually a newspaper, just a daily hate filled xenophobic lying rant

happygeek commented: Sadly correct on both counts +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No, changing the names of the local variables will still leave the class variables uninitialised!
The mistake is to re-declare those fields/variables in the constructor. You do not want local variables that duplicate variables declared in the class.
Just declare them once, in the class, and use those everywhere, including in the constructor.
You can then initialise them where they are declared in the class, or initialise them in the constructor, whichever you prefer.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes.
I was amazed by the performance. Loading the map with over a quarter of a million words from an official scrabble list takes under a second. Searching for anagrams goes as fast as you can type (which you would expect with a tree map), but searching the original strings for words with some specified letters in particular places is also seemingly instant. I didn't implement searching for anagrams with specified letters in specific places, but that woud be very easy and also instant.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

After that discussion I implemented a general version that works correctly. It takes each word in the dictionary and sorts its letters into ascending order then adds that to a Map (sorted letters as key, list of matching original words as value).
To make searching faster I actually created an array of maps, one for each word length, but that's maybe over-thinking it.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Given the simplicity of the showAll loop, there really are two instances of Carol, so either that's what the test run input data had, or its a bug in the insert method. Without seeing the actual test data I can't comment on that.
But your insert and fetch methods have the same uninitialised loop var i problem as showAll had.

ps: Why the deepCopies? If I put something in a tree and later retrieve it I would expect the original object, not a copy of it.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

and if you are still stuck... <spoiler alert>

you declare 4 text fields in your main class.
you declare 4 more with the same names as local variables in the constructor. This is not technically an error, but 9 times out of 10 is not what the programmer intended. The constructor initialises the local variables. When the constructor returns, those 4 variables go out of scope and are discarded
in your actionPerformed you try to use the 4 variables from the class, but these were never initialised, so they are null.

If you use a full-scale IDE eg NetBeans, you will see a warning like "Local variable hides a field" when you declare the local variables

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

A null pointer means an unititialised variable (or a return value from a method that returns null)

at Chapter12.TheaterGUI$buttonListener.actionPerformed(TheaterGUI.java:84)

You have the original code, so you know which line that refers to
So check that line to see which variable is null (if in doubt print them all)
Then follow the logic back to see why it;s not initialised.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There's no excuse today for <etc>. Unlearning is harder than learning.

That is the excuse why teachers continue to use outdated materials

rproffitt commented: I get it. The teacher must unlearn. We have asked for too much! +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Harish

  1. Your code is unreadable - a solid mess of undocumented stuff strung end-to-end without any thought towards making it comprehensible. It even has gotos! It's useless.

  2. Can someone do the AI part of your school project for you? As in cheat? As in get an unfair advantage over your peers who actually do the work themselves? As in waste your teacher's time by not bothering to learn what this exercise is supposed to teach? Guess what... the answer is no.

Come back here with code we can read, make a serious attempt to do your own homework, ask sensible questoins, and we will help.

Reverend Jim commented: You beat me by 22 seconds. +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 49 you fail to initialise i (which is also used in many other methods) so your loop may or may not execute any number of times.
Insert prints "true" because that’s what the insert method returns

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Well, the people who wrote it know how. They even documented it on the web. You even posted a link to that very page as part of your question! What exactly is it you need to know that’s not covered there?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It looks like the spec is badly written
Although the method is called "printAll Nums" the spec does NOT say print the numbers, it says return a string (that could be printed).
So, don't be distracted by the misleading method name, just read the spec carefully and return "the string s, followed by a colon and a space, then followed by the number of times that string occurs in array b" (and you can then test it by printing the returned string)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Pietiläinen

Just a guess...

Is it possible that you are using a one byte character set where the a-umlaut is a 2-byte extended code? (easy to check - just replace it with an ordinary a and see what happens)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi zebnoon
Sorry, but it does look like there's nobody around at the moment who can help you.
People do have very full and busy schedules, but with any luck someone with the necessary knowledge will get a free moment t help you.
JC

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

http://bfy.tw/F8Mq (Second hit)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Need code <copy of teacher's spec>? No.
You first need to learn to be polite and ask sensible questions.
You obviously ignored the "Read This Before Posting A Question" topic at the top of the page. Read it now, then start again and someone will help you.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

tell me how i insert data in to data base, how to select the data in the database

There are many many tutorials on the web that cover this very basic information. Nobody here is going to write a new one just for you. Do some research of your own, then come back to Daniweb and start a new topic if you have any sensible questions.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

What about initComponents? You need to have at least one control in the JFrame to get something worth seeing (unless you are using absolute sizing...)

ps: You are probably getting a visible JFrame thats just a few pixels big hiding at the very top left of your screen

rproffitt commented: "Your app in a pixel!" +12
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Not in Java

??? Object[][[] is a multi-dimensional array that holds anything.

Because every object extends Object, and primitives are auto boxed/unboxed into the corresponding objects as required, then you can put anything into a multi-dimensional array of Object (including other arrays).
Having said that, it's a terrible idea. You bypass all Java's type checking, so code errors will be hard to find, and before you use any of those Objects you will have to do an unsafe runtime cast to String, Image or whatever. And the code will be really hard to follow.

Let's try thinking in Object Orientation instead (after all, this is Java)...

Why not create a Joke class, with text, image etc as instance variables, and then it's a simple array of Jokes. All the variables are strongly typed, so fewer errors, and extending the app with more info about a Joke is trivial. Plus, the code will bo so much easier to read and understand.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A couple of notes re the above:

The discussion of divide by zero seems to be looking at the wrong variable. It's not the miles that are the problem, its the mpg that cannot be zero.

As rproffitt points out, using an if/else to decode a boolean is highly redundant, so

    if(gasInTank == gasNeeded)
    {
        return true ; 
    }
    else
    {
        return false;  
    }

can just be

return gasInTank == gasNeeded;

ps Opinions vary about how to bracket code, but the norm for Java, as used in all the code for the API as well as all Oracle's samples, documentation and tutorials, is

        if(gasInTank == gasNeeded) {
            return true ; 
        } else {
            return false;  
        }
rproffitt commented: Thanks for the better example. From 8 to 1 lines of code helps in many ways. +12
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Look again at line 10. Did you really intend to set pos back to 1 , 2, 3 etc? Or were you hoping to set it just after the last place where you found the substring?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You have an unmatched ) on line 5

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Adam

That's hardly surprising when you revive a year-old thread. And be careful when referring to other people's posts as "random garbage". You have been warned.
JC (Moderator)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That question is so vague that nobody could answer it sensibly. Please explain EXACTLY what you are trying to do, what you have done so far, and exactly what is preventing you from progressing.
ps JDateChooser is not part of the standard Java API, so also specify where you got yours from and which version it is.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I don't mean to be picky, but a loop that needs to be executed at least once should be a do/while not a while, which would obviate the need for that faffing around with a quit boolean.
As in

do {
   (whatever)
} while (user wants another game);
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe you could use a try/catch for any Exception at the highest level in your code and see if you can output the message from there?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry, I’m all OSX, IOS, Win10, don’t know android at all.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Look at line 127

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

“Crashes” doesn’t tell us much. How about an error message and a stack dump?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Re noobs... I have been worried about the aggressive responses to some recent cross posts. Nowhere in advance do we tell them not to do it. Maybe the majority of those were not aware of our views on that. I certainly think we should respond politely, at least the first time.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

When you try to call those methods you are missing parameters or using parameters of the wrong type.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Anyway where are the rules?

Yes indeed. I think it's poor practice for us to penalise people for breaking rules they don't know about. A link buried in the TOS ("Yes I have read and approved the TOS, all 18 pages of legalese") doesn't count. There was a time when there was a direct link at the bottom of each page. Much better IMHO.

I think we should have a highly visible link to the rules on the page where people create a new topic - maybe even require a tick against them.

Mr Prosser: you found the notice, didn’t you?

Arthur: Yes yes I did. It was on display at the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying beware of the leopard.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's more or less my understanding too - order of execution was left undefined/unspecified in places where the experts thought it would allow compiler writers more scope for optimisation. Nowdays we know that (with a very few exceptions) the last 1% of code efficiency is not a problem, but software maintenance and porting are massive issues.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Smart people ... decided that it was best to make stuff like this undefined

Yes, I did understand that. My opinion was formed including that knowledge. I'm more worried about the people who moved into that house, turned some stuff on, and lost everything in house fire that should never have happened. :)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's a definitive reference on order of evaluation
http://en.cppreference.com/w/cpp/language/eval_order

Note about half way down ("Undefined behavior") it discusses ++x specifically. Apparently it used to be "undefined", now it's just "unspecified". And people use C++ for real-life applications? Terrifying.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No reply from a C++ buff yet? At the risk of making a fool of myself I'll try.
I'm no C++ expert, but this looks to me like another example of C++'s "undefined" behaviours - specifically the order in which things of the same priority are done within some expressions is not defined (the order is only defined at specific checkpoints (I forget what the C++ term is), but not inbetween). There's a much-discussed variant of your problem in which various x++, ++x and x values are used as parameters in a function call which suffers from the same problem.

rubberman commented: Actually, they are well-defined behaviors for both C and C++ +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

To be fair, 266 of those lines are GUI code generated by NetBeans, never intended to be read. It was pointless posting that part.

In the actual code the choice of member names is not so bad, so the code is not that hard to read.
Having said that, some explanation of what its all about would certainly be helpful.

In the interest of full disclosure: divinity02 and I have had many conversations over the years. She doesn't find programming easy, but makes up for it by hard work and persistence. I think that's worthy of support, so please don't be too harsh.