JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A small point:
line 8 you return in the if construct, so the else and its associated brackets are redundant. This is a very common pattern (it's called a guard )...

myFunction(params) {
    if (there's something wrong with the parameters) 
          return errorvalue;

    // no need for an else here, just get on with it!

    do rest of function
}
AssertNull commented: Good point +7
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The surfing is still a nested loop potentially with On^2 (depending on how many zeros there are). Similarly Adam and Danis solution is also potentially On^2

You can make one pass ascending and set each element to its distance from the previous zero, then a second pass descending overwriting any element whose distance from the previous zero is lower. Guaranteed On. I'll post code in a minute

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Take another look at the other functions because they still contain a lot of fat just like you removed from the first fn. Otherwize it's OK.

Purely to help learning, here's some working code that shows a slightly different way to look at it, while showing how much fat there still is. (The code is Java, beause that's my bag, but at this level it's the same as C++ apart from the print statements.
First - a fn to generate the sequence:

    // generates Hailstone sequence with initial value = start, 
    // calls analyser for each value in the sequence
    void generateSequence(int start) {
        int n = start;
        while (true) {
            analyseValue(n);
            if (n <= 1) return;
            n = ((n % 2) == 0) ? n / 2 : n * 3 + 1;
        }
    }

All it does is generate the sequence, but as it generates each value it passes it to a separate analysis fn. To me this seems a good way to split the functionality because you can change that to perform any other analysis withot needing to do anything to the code that generates the sequence (separation of responsibilities).
This analysis fn prints each value, calcs the length of the sequence, and records the max value in the sequence...

    int length = 0, max = 0;

    void analyseValue(int value) {
        // get passed each value in the sequence for analysis
        System.out.print(value + " ");
        length++;
        if (value > max) max = value; …
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm sorry to say that me eyes crossed when I tried to read that code! It's way too complex. and the temp variables are not needed.
Looking at all your code I see a lot of unneccessary temp variables, and I wonder if there's some misunderstanding that's causing you to think that you need them?
For example

    void hailstone_Sequence (int n)
    {
        int value = 0, temp = 0;
        cout << n << " ";
        while (temp != 1)
        {
            value = next(n);
            temp = value;
            cout << temp << " ";
            n = temp;
        }
    }

doesn't need those variables, this will do:

    void hailstone_Sequence (int n)
    {
        cout << n << " ";
        while (n != 1)
        {
            n = next(n);
            cout << n << " ";
        }
    }
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi
Firstly, I have to confess that C++ is not a language I know well, so I'll confine myself to the logic which would look much the same in Java, Swift, C# etc.

That code looks OK to me. There are many small redundacies (eg lines 82-85), but they are nothing to worry about and you will get better at that as you progress. More importantly the way you have packaged the code into functions makes the program easy to read and understand, and keeps any redundancy sensibly low.

I'm not saying that's how I would do it, nor am I saying its the best way, but it's perfectly acceptable from someone who is still learning the basics. With that code as a template and the hints I posted earlier you should have no difficulty with the max number.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Function next... is this supposed to return the single next number in the sequence? If so it doesn't need a while loop - it's only calculating one value. What happens in your existing code is that it always encounters one or the other return, so the loop never enters a second iteration.
ALso, since next is a private internal function its not the place to test for invalid input (n<=0). You should test for that just once, before starting to make repeated calls to next

This leaves you with a much simpler structure

private next(n) 
    if n is even return ...
    else return ...

public hailstone(n) 
  loop
       update output, length, whatever
       n = next(n)
       if n=1 return

main
    get starting value for n
    reject/retry value if n <= 0
    hailstone(n)
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The largest number in the sequence is: (Problem line)

In general... you have a loop that is generating a sequence of values and you want to know the largest one

largest so far = 0
start loop
    if value > largest so far
         largest so far = value
 end loop
 largest so far now contains largest value from the sequence
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm having trouble coming up with a way to print the max and this line "The longest hailstone sequence starting 7 with a number up to has length____." for the output.

You don't explain exactly where you are stuck, but all you need is something like

for i = 1 .. 7   (pseudocode)
       length = hailstone_Sequence (i)
       keep note of largest length found so far
print "The longest hailstone sequence starting with a number up to has 7 length " + largest length
rproffitt commented: That's a start. +11
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No need for an array, just read each line from the file, calculate the price x num tickets, add that to a total that you initialise before starting to read the file,

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

More thoughts on Observer...

If all you are doing is creating Pizzas then the GUI can call methods to set the size, ingredients etc, then call another method to get the cost or whatever. No need for Observer.
But if you want to include cooking and serving the Pizza then Observer would kick in, ie

The Pizza has states (ordered, being cooked, cooked ready to serve, being served, served, paid for) that change over time. You want those to be visible in the GUI. You could have the Pizza class call a method in the GUI when its state changes, but that means the Pizza class won't work without that specific GUI (eg if you are running from a test data file).

So you make Pizza Observable , which means something like:
Define a PizzaListener interface with a method likevoid pizzaStateChanged(newState).
Implement PizzaListener in your GUI,
Give Pizza an addListener(PizzaListener) method
GUI uses that method to add itself as a listener to each Pizza as its created.
Every time the pizza's state changes, call each listener's pizzaStateChanged
Now when the pizza's state changes the GUI method is called and the GUI can update its display. But the code for Pizza is in no way dependent on the code for, or even the existance of, a GUI.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If that's what your lecturer wants, then yes, you have to supply it!
Having said that, apart from the user interface itself I can't see where Observer pattern is relevant. The whole of GUI event handling is classic Observer, but that comes as part of AWT/Swing - you don't have to develop it yourself.
Maybe there are other parts of the spec that we haven't seen, in which Observer is applicable?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Which web site do you mean? Anyway, just Google - there are dozens or even hundreds of them.
From what you have posted so far it's not obvious to me how it relates to your current exercise.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, I do know about Observer pattern. It's how Swing event listeners work. You create a Listener (Listener, Observer - they're the same thing) and when things happen or stuff changes your method gets called with the new info. You have to know about the class that will create the event, but that class doen't need to know about you

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi D2 - hadn't noticed that it was you! :) JC

Sketching out a GUI is a good way to understand the requirements etc, but it's NOT the place to start actual development.

This is an OO exercise, so start with the objects. Look for the important nouns in the problem description - for example Restaurant, Order, Baker, Cashier, Pizza, SIze, Topping, Crust... (maybe you don't need those exact classes, just see how it works out when you add the members and method signatures).
Then hard code a couple of test cases and get all the logic working.

Then design and code the data file processing, which will incidentally give your logic a pretty good test. Think of this as an alternative "user interface" for your classes - so you have one set of classes that represent everything about the restaurant, and two separate ways to use them, one from file , one from GUI.
...
Then and only then create a GUI that uses the functionality that you jave already created and tested. (You may want to add a few more methods to your classes specifically to support the GUI, but these will become obvious when you start coding the GUI.)

When you do, finally, get round to coding the GUI you will find excellent examples and explanations for working with radio buttons etc in the usual Oracle Java Tutorials

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you pop all the numbers used in a sucessful sum then you will not be abl to use any of those numbers in any other solution, eg with 2,3,2,1 you will find 2,3 then pop those values leaving 2,1 and thus never find the 2,2,1 solution.
This problem requires you to traverse all possible subsets of the array with pruning of branches that meet or exceed the target. Traverse all subsets can be done without recursion, but recursion is by far the cleanest approach.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi Scheppy

Picking an unknow number of entries from an array of unknown length - you will have problems coding this with ordinary loops because you won't know how many loops to code. It has "recursion" written all over it. Eg

array contains 1,3,4,3,5,8,2,1, target is 5

   take the 1, array now contains 3,4,3,5,8,2,1, target is now 4
   target is >0, recurse to find solution in the remainder of the array
      take the 3, array contains 4,3,5,8,2,1, target is now 1
         take the 4, - target exceeded, go no further
         take the 3, - target exceeded, go no further
         take the 5, - target exceeded, go no further
         take the 8, - target exceeded, go no further
         take the 2, - target exceeded, go no further
         take the 1, - target met - we have a solution!
   take the 3, array now contains 4,3,5,8,2,1, target is now 2
        ...

Note: when you hit the target, record the indexes (you can worry about that when you have working code that finds the required values)

Think about that... if still stuck come back here for some more hints.
JC

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. This is pushing the limits of my C++ knowledge (I despise C++ ... should have been strangled at birth) but:
You need B and C each to have their own variables, ie not inherited from A.
I know that for functions you can declare a virtual function in A, and implement it in both B and C which will work exactly as you describe, but as far as I know there's no virtual equivalent for variables. If so you can wrap the variables in accessor methods that are defined virtual in A.

There are probably solutions involving casting pointers to the classes, but that way madness lies.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your question doesn't seem to make sense.

You have one variable x that is defined in A and inherited in all its subclasses.
That variable can only have one value at any one time.
The constructors set x variously, and the value of x will be the last value set in any constructor.
When you create an instance of a class all its superclass constructors are called before the subclass cobstructor is executed - this is fundamental to how inheritance works.
After creating the instance, x will have a value that you can print.

What do you imagine happening when you ask "i should be able to print the both sets of the values". Where do you imagine the other other values will be?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, don't worry about your English - we will communicate somehow!

Perhaps you are re-initiasing the array somewhere? Maybe the problem is in info_add? Without all the code it's hard to see.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Look at line 18
If you try to create a value greater than 3 this will reject it

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Seriously - you commented out line 13? Are we wasting our time here?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Go to http://www.oracle.com/technetwork/java/javase/downloads/jdk-netbeans-jsp-142931.html and download the JDK/NetBeans bundle for Mac OSX. That's everything you need in one package.
It's a standard Mac disk image installer, coudn't be simpler.

When you get your code running with all the errors displayed you will find that the ~ is a problem. Come back here when you get to that stage and I'll walk you through the fix.

JC

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, I did come on strong about obsolete versions of Java, but I'm not going to apologise. There really are hideous exploits for older versions of Java in the wild, and if you don't replace them with a currently-supported version you are definitely at risk.

Anyway....
A clean download/install of the the current JDK and Eclipse versions should run perfectly. You could also try NetBeans, which is my personal preference for Java development.
What OS are you on? Looks like Linux or MacOS from your use of the ~

rproffitt commented: I agree. Nothing wrong with pressing how bad an idea it is to use older versions of Java. +11
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry. C, C++, C#, C no evil... the're all the same to me. But is there ANY language in which 25%2 is 5?

Decepticon: yes please, please do share that proof!
JC

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm no expert at C++, so can someone else look at this and see if I'm missing something?

zachattack05 : 25 % 2 would return 5

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It depends on your employer. Most companies expect you do attend meetings, drink coffee, document your code, fill in time sheets etc etc. Others expect you to code 22/24 hours for peanuts and treat you like an idiot slave. If you have any empathy sensors at all you will se the difference in their interview styles and questions.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

This really is the easiest way... for example here's all the code to run a ls (list directory contents) command and display the output and any errors.

    ProcessBuilder pb =  new ProcessBuilder("ls");
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError();
    pb.start(); 

(plus 4 lines if you wrap that in a try/catch/printStackTrace())

You don't need all that
ArrayList<String> commands = new ArrayList<String>( Arrays.asList(cmd.split(" ") ) );
stuff. Just
ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));

Re your latest errors:
Are you using an obsolete version of Java? You should be on Java 8 by now, but the above code just needs Java 7. If you're not on a current Java version then you are danger to yourself and those around you - you are missing years and years of critical security fixes and expose yourself and everyone around you to highly malignant malware.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you want to see the output and the errors from your process the the simplest way is to tell your process to inherit its output and error streams from your java program...

    ProcessBuilder pb =  new ProcessBuilder(... etc
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);

This will make your process send its normal output to System.out and its error messages to System.err. That's all you need.

ps: If my guess is right there is a message about the "~" directory waiting for you in the process's error stream ;)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You are confusing exceptions and process errors. You need the catch for your java program errors. Your process may issue its own error messages which will go to its error stream. For those you have to capture the error stream or redirect it to std out which you are already handling
I'm just on my phone right now, so I'll answer the array stream question later.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I will definitely print the stacktrace from now on.
See line 26

You're still not displaying the Process's error stream - which is where error messages may be waiting. (all you need is a pb.redirectErrorStream();)

Which OS are you using?

ps Just a question: Why all the faffing about with a byte array stream?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

First thing is to fix that terrible catch clause.
If/when there is an error you just told Java that you didn't want to know anything about it, and please discard the detailed error message that Java just created for you.
ALWAYS put an e.printStackTrace(); in your catch blocks until/unless you have a good reason to do something else.

Second thing: You read the standard output from your Process, but you ignore its error stream, so you won't see any error messages it generates. Best to read/display that as well.

There's a good chance that these two things will give you the info you need.

Last thing: Runtime.exec was replaced over 10 years ago by ProcessBuilder, which is much more powerful and avoids many problems. You should replace this code with the ProcessBuilder equivalent. Google for details and examples.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
int cumulatedMillions = 0; // declared outside listener method

// inside listener method...
if(carsJComboBox.getSelectedIndex() == 0)
{
    cumulatedMillions += 250;
}
if(carsJComboBox.getSelectedIndex() == 1)
{
    cumulatedMillions += 500;
}
currentCarsJTextField.setText(cumulatedMillions + " Million");  
// needs to be more clever for billions

// or could define array {250, 500 ...} and use getSelectedIndex()
// to index into it, thus avoiding all those if tests
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Are you sure that code is being executed? Maybe there's a problem with your listener. Try printing the selected index in those if tests to confirm.

You can have a "total" variable that you add 250 or 500 (etc) to in your listener the set the text field to
total + " Million"

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I asked exactly what help you needed. If you can't answer that then nobody can help you.
Before going any furher read this excellent guide on how to ask for help
https://www.daniweb.com/programming/threads/435023/read-this-before-posting-a-question

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Exactly what help do you need?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Could it be the empty Strings ("") you added to the table at the end? Try zero instead for the numeric column?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's interesting that the stack for your error doesn't include any of your code - it's just Swing re-drawing the JTable. So the exception is NOT being thrown from any code that you wrote. The implication is that you, at some earlier time, populated a cell that should be numeric with an object that isn't numeric or capable of being converted to a number, and this blows up when Swing tries to display the table.
So I would go back to the code where you populate the table's model (lines 40, 43 etc) and print all the values you use to populate numeric columns to see if any is unintended.

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

Yes. My algorithm was 2d, just the illustration was 1d, and it extends to nD. But yours still looks a lot better :)
JC

ps what about 2,4,4,6,6,6,6 -> 1,1,1,2,2,2,2

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe sort the list based on the first value. Then it's trivial to find consecutive entries that are within tolerance for the first value. For each set of such entries sort it by the second value and find the subsets that are within tolerance for the second value. Replace those subsets by their averages.

ps there are multiple solutions, and this may not find the optimum one (if "optimum" has been defined!).
Eg with 1, 3, 3, 5, 5, 5 ,5 the "best" solution could be to group all the 3s and 5s, but a single pass sequential algorithm may group the 1 and the 3s, then start a new group for the 5s

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Interesting discussion,
You convinced me that there are real use cases for turning logging on and off, so my only beef there is that I think it should be on by default so the simplest cases really are simple.
Don't know why you had that focus issue with file save dialog. I've never seen that myself, and i know that you are not supposed to need anything yourself to manage the focus.
It's funny how old-time coders can't see how clunky and convoluted the traditional for loop is, especially if you just want to loop through all the members of some collection. For a beginner I would start with the simple "enhanced" for loop, and only get into the three-arg for construct later.
Java 8 has been the current version for more that 2 years now. When are we going to start promoting the many superior features of 8 if not now?

(All the above is, of course, just my personal opinion!)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

More thoughts...
I think the default for logging input should be true, so all you need to do is write the data at the end. The setter would only be needed if you wanted to turn logging off, although I still can't see a use case for that.

As for writing the file, maybe we should set a good Java 8 example by using Files.write(path, userInput); Or at the very least use an enhanced for loop.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The error message should include a line number... that's important

Anyway, line 82 of the second class refers to mortgage, which is a variable in the first class. You don't need that to call a method in the same class. You can just say calcC()

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Excellent!
Thinking more about the use case, I wonder if it would be more useful to use a standard file save dialog for saving the input? Maybe a no-args overload of writeInputToFile?

Thanks for the pm. I'll deal with that when I get home next week.
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Reading all this again I'm not sure where we stand on the logging thing... did you agree with my suggestion of adding everything to a List and having a method to save its contents? Did you keep the start/stop logging thing, and if so, what's the use case for that?

If you pm me your email address I'll set up a Dropbox shared folder where we can sync the full code and only post stuff here where it's new or interesting. No hurry, I'm here on hold until middle next week with no IDE or compiler.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, I think you and I have converged nicely. What we really need now is some more input.
Jc

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Ok, good work!
Re logging: right now I'm against it and see it as an unnecessary complication. I'm especially against messing up the second constructor with a cryptic Boolean to support it. I would much prefer to leave that constructor alone and add a separate method to set a log file for the (few?) people who may use it, e.g.createDataFile(file)
As I said before, by the time our novice has got his code to the point where he can enter all the data without crashing, it's too late to be really useful.

Edit: after yet more thought here's how I would now do it...
Always append all user input to a List<String> as it is entered. Then createDataFile() opens a standard save dialog and writes the contents to the file.
So the use case is:
User does test run. Gets to end. Decides it's worth keeping this data. Creates data file.
... which makes more sense to me.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A couple more thoughts on logging...
If we want to do it it's a single println echoing the user input in getString, plus some trivial method to specify the output file.
However, thinking about it... its only going to be useful if the user enters a complete set of correct data, but while their code is under development they won't be able to do that because their code will crash first. So I'm happy to let them create their test data in an editor.

Since you made those improvements and I don't have a Java IDE for the next week it seems you are de-facto guardian of the latest source.
So maybe you can add a small thing I thought of. Novices get messed up with files because they don't understand the default locations that Java uses for simple file names. So in the constructor with the file name I would like to print the file's absolute path by way of confirmation of exactly what's going on. That's just un-commenting the debug print in my code and adding a bit of text like "running with input data from ”+file.getAbsolutePath()

Have fun!
Jc

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Many thanks for that excellent feedback, and for improving the commas regex. (NB: the decimal point is also locale sensitive - eg in France it's a comma). I'm no regex expert either! I agree that regex is not for novices, but as long as they are not exposed in the public API then I see no problem.
As for the sequence of messages... ordinary output is going to System.out, but the exception is being reported on System.err. They are both going to the same device, with unspecified buffering, so exact sequence between them is uncertain.
isYes should indeed trim. I'm nervous about putting that in getString without being sure that no use case will be sensitive to leading or trailing spaces (eg indentation?)
I'm sticking to the idea that file input is only for automating console input, so multiple fields per record etc are things that I'm happy to ignore, or leave to Scanner. I'm sure David will agree.
Finally, I think I'm beginning to appreciate the thinking behind your logging idea - automatically create an input file that reproduces the current manual run's test data.
Excellent contribution all round, thank you
JC

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. I'd also appreciate your feedback on my code if you have time - I intended it as a serious example of how to meet the objectives in good Java.
As for the "official" DaniWeb position: as moderator of the Java forum for many years, it would be me who would publish or pin the thread or the final code for future reference. However, when it comes to discussing and selecting versions no mod has any more authority than any other member - in that respect we're all equal here, with equal power to encourage or discourage and support or deprecate (provided nobody breaks the Daniweb rules). If we can't all converge and agree on something then we'll just let this thread die a nautral death, and anyone is free to post whatever of their code they believe is worth posting.
JC