Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Tesseraction
Apr 5, 2009

Aleksei Vasiliev posted:

This is obviously at least partially a Windows problem but I have no idea what's going on with that last thing. Is all of this Windows issues? Is there any way around it?
(not using code tags since they choke on non-ASCII text)

I hate to be the one who says "well it works for me" but using your


PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println("Алексей Федорович Карамазов был только он, "
+ "несмотря даже заметил, так именно и оба");


I got the correct output. What version of Windows / the JDK are you using, have you updated to JDK7?

Adbot
ADBOT LOVES YOU

Tesseraction
Apr 5, 2009

Does this little piss-around solve the issue? It seems like it should help.

Tesseraction
Apr 5, 2009

Hidden Under a Hat posted:

Yes, the class int[] is ballooning up to over 100 MB, after several invocations of that method. None of the int[] objects that I'm using could possibly cause that much memory to be used, so I imagine it's something that the JFreeChart library is using, which is why I believe chart objects are persisting even though I'm only using one Chart object and reinitializing it when the settings are changed.

What are you storing the int[] in? Is that object serialisable? If so, try using reset() to clear any leaking references.

Tesseraction
Apr 5, 2009

It's called a "fold" in Haskell / functional languages.

There's an article discussing implementing it in Java here. Not sure if it's any use for you, though.

Tesseraction
Apr 5, 2009

Shouldn't you be using \n instead of %n in that line?

e: in the time it took me to post you already realised

Tesseraction
Apr 5, 2009

Try casting your Graphics to Graphics2D (if you haven't already)
code:
Graphics2D g2 = (Graphics2D) g;
and use its setAffineTransform and transform functions, making sure to reset the AffineTransform after drawing a particular shape if necessary. Use Graphics2D's setPaint with GradientPaint for your gradient. It can fill any Shape you send it.

Tesseraction
Apr 5, 2009

Uh, maybe I'm missing something but
code:
JCheckBox a = new JCheckBox();
		
boolean b = a.isSelected();
works for me?

Tesseraction
Apr 5, 2009

Java has a habit of making you jump through some ridiculous hoops but for something as (relatively) fundamental as a check box it seemed hilariously out of touch to not have something easier than that chain of calls, but then again when this is JavaFX's Hello World I remember why Java still deserves these jokes. Not to mention the shittiness of the Visual IDEs.

Tesseraction
Apr 5, 2009

Following on from what Joda has said, I can see where your mistake is, but for the sake of helping you learn to debug, what IDE do you use?

Tesseraction
Apr 5, 2009

Joda posted:

Actually, as far as I can tell the loops work as they should. I've made it run as intended, and the only fixes I have made are syntactical.

Try putting in numbers larger than the length of the array - the issue will be made clear in a minute, I hope!

signalnoise posted:

They have us using Eclipse

Good! That saves me having to re-install and re-learn the NetBeans IDE before replying.

Before I begin, I'll show you changes I made to your code:

code:
package chapterSix;

import java.util.Scanner;

public class Eighteen {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		
		System.out.println("How many numbers would you like to sort?");
		
		double numbers[] = new double[input.nextInt()];
		
		System.out.println("Please enter " + numbers.length + " numbers.");
		
		for(int count = 0; count < numbers.length; count++){
			numbers[count] = input.nextDouble();
		}
		
		sort(numbers);
		
		System.out.println("If I sort them, those numbers are " + printArray(numbers));
	}
	
	static String printArray(double [] array) {
		String s = "[";
		for (double d : array) {
			s += d + ",";
		}
		return (s.substring(0, s.length() - 1)) + "]";
	}
	
	public static double[] sort(double array[]){
		double temp = 0;
		for(int outerIndex = 0; outerIndex + 1 < array.length; outerIndex++){
			for(int innerIndex = 0; innerIndex + 1 < array[innerIndex]; innerIndex++){
				if(array[innerIndex] > array[innerIndex + 1]){
					temp = array[innerIndex];
					array[innerIndex] = array[innerIndex + 1];
					array[innerIndex + 1] = temp;
				}
			}
		}
		return array;
	}

}
I changed the names of two variables so make them easier to distinguish. I can sympathise with using var1, var2, var3 when doing something quickly, but it can confuse the gently caress out of you. The only real change is that new method I added

code:
static String printArray(double [] array) {
	String s = "[";
	for (double d : array) {
		s += d + ",";
	}
	return (s.substring(0, s.length() - 1)) + "]";
}
This was just a kludge for printing the array in [1,2,3,4] form. Look at it if you want but don't learn from it as it was done for speed not efficiency.

Anyway, a guaranteed way of breaking it is trying to sort [8,7,9,6], which totally isn't my PIN number. Putting it in gives me this:



for reference, each line of the error specifically says where the issue was raised - so in this case an ArrayIndexOutOfBoundsException was raised by Eighteen.java's code at line 36, specifically its sort method: at chapterSix.Eighteen.sort(Eighteen.java:36)

And the next line says that sort method was caused by line 19. Well that's nice but knowing is only half the battle. Eclipse, like many IDEs, is nice enough to make it a hyperlink to the line in particular, so clicking at chapterSix.Eighteen.sort(Eighteen.java:36) takes us here



well okay, so this is obviously a problematic line. Here's where the debugging gets to start! Let's juuust right click on the side area:



Right-clicking on the blue vertical line on the left gives you the menu I have there. Click on Toggle Breakpoint and the blue dot on the context menu should appear in the blue column. Is yours on Line 36 or its equivalent for you? If so, we can start the Debugger:



mine's there, if it isn't, pressing F11 will bring it up (Ctrl + F11 will be a non-debug execution), or use the Run menu where it's right next to Run.

either now it'll ask you if you want to open the Debug perspective, or it'll ask you to enter the numbers then ask (more likely). Say "don't ask me again" and yes and you should now see something similar to this:



I made it smaller to fit in a normal post, but it should look something like this. An area of particular interest is the top right:



we'll come back to this in a minute. The other point of interest for now is the bar at the top:



We'll be using two of these here, because I want to simplify the debug process for now. So it's good old Mr Continue:



As you might have guessed from the combination of the pause sign and the play sign, this tells the debugger to run as normal until the next breakpoint. At which point it pauses as we were before. Now, going back to the variable window, click on the arrow by the array and you should end up with a window like this:



or something similar I hope. If you have, press Mr Continue and you should get this:



I'm hoping you've (firstly, got the same result, but more importantly) picked up why the values are yellow? Eclipse has helpfully told us what changed. Now, what I'm going to do here isn't very efficient debugging - IMlemon has shown a common (and effective) way of doing it more efficiently, but for the benefit of learning debugging, I'm doing it the long way: pressing continue again gives you this:



innerIndex is now 2, and so the next array index to be worked on is [2], which is currently 9.0. So if we press Continue again we should get:



Looks good. I admit the yellow highlighting here knocks my eyes off balance and makes it look like the array has five entries, but obviously that third yellow line in a row is the value of temp. innerIndex is now 3, so array index [3] is about to be looked at, so if we press Mr Continue..



Well okay, that makes sense, 9.0 isn't smaller than anything else in the array, so it's fine. Now what happens when we do the next iteration of the algorit--



well drat. Actually now I think about it, what did it say to the left earlier:


timestamp different because I buggered up screencapping it

Thread Suspended? Well I guess we need to go back at least one step. Back to:



So we're back here. Time to go back to the bar of symbols and pick out a slightly finer magnifying glass:



This fella, Step Over, is useful - it moves line by line. The one to the left (Step Into) dives deeper (looking into every action on a line), but we won't use it because it's a) more information than we need b) going to give you an error unless you installed the full Java source from Sun, which no-one does unless they need it. You can use Step Into on your own code, but that's not useful right now. If you press it once or twice you'll see the Index(...)Exception occur, and if you look it was at this point it occurred:



which is on this line:



So we have if(array[innerIndex] > array[innerIndex + 1]), or if we parse it (using the Variables from the screenshot):

if(array[3] > array[3 + 1)

or

if(array[3] > array[4])

I'll pause here because of post length, but can you see what the issue is with this statement? I'll add a hint just to be patronising: and array's first index is 0, so the last index is the length minus one. I'll continue once you've replied.

Tesseraction
Apr 5, 2009

Joda posted:

E2: In addition to what Tesseraction is walking you through, you need to tie the sorted array to a variable (you can just use array,) for it to be in scope in main(). I discovered this just now, but apparently Java makes a copy of an array when it's passed to a method rather than pass a reference.

Yep, that's calling by value. In C++ and related languages you pass 'by reference' only if you use pointers. Calling sort on an array changes depending on your intended behaviour:

code:

static int[] theArray;

int [] functionA(int [] input) {
 return input;
}

void functionB(int [] input) {
 theArray = input;
}

int [] functionC(int[] input) {
theArray = input;
return theArray;
}
effectively show how different methods can 'work on an array' without doing the same thing.

signalnoise's METHOD is of type 'A' - working on an array and then returning the modified array, but their IMPLEMENTATION of it is calculating a sorted array but not assigning it, thereby treating it like 'B' even though the desired result needs to be stored somewhere.

Tesseraction
Apr 5, 2009

TheresaJayne posted:

when you have been programming for a while you KNOW what the problem is..

Oh definitely, and for the example we can quickly see what the issue is, but debugging principles are easier to teach with problems like this one where the answer is 'obvious' and can then be extended to more complicated scenarios.

Tesseraction
Apr 5, 2009

According to the first pastebin that's because you never initialise mySolo or else initialise it to null (line 12). Have your method check if it's set to null and if so to initialise it with the current note in cur.

Tesseraction
Apr 5, 2009

Actually, just try setting mySolo to null when the object is created? I admit I haven't tried running it as I don't have the library right now but it looks like you've not put any guards against a variable being uninitialised. Try setting mySolo to null in the other constructor... or is that constructor meant to be setting mySolo to the value of the passed Phrase?

Tesseraction
Apr 5, 2009

What operating system / IDE (if any) are you using?

Tesseraction
Apr 5, 2009

I may be wrong, but if you use -classpath don't you have to put the path into double quotes? I think no double quotes is with -cp for the short version.

Tesseraction
Apr 5, 2009

an skeleton posted:

Can someone tell me why I suck and therefore can't draw a Line.

code:
Graphics2D g;
		g = new Graphics2D();
		g.drawLine(1,1,5,5);
I have this code in a class and pretty sure all the right things imported. It says I can't instantiate the Graphics2D class, is there some other way you are supposed to make an instance of this class? Thanks

Just to make this explicit, you'd get your Graphics context by calling a Component's getGraphics() function. You'd probably want to call it from a Canvas object in a JPane or some such.

You can cast a Graphics object to Graphics2D with no issues.

Tesseraction
Apr 5, 2009

Well you could look at the page and figure out how the onclick method fetches the next page, or you can ask Stack Overflow and get suggested to use this library to provide what you need. You still need to inspect the page you're scraping to know what its 'next page' button is, though.

Tesseraction
Apr 5, 2009

If you're working entirely 'headless' (not strictly the definition, but if you're working straight from a terminal interface then y'know), you might have to use heuristic guesses of searching through (X)HTML tags for something suggesting the word 'next (page)' and then looking around that for an onclick method.

Tesseraction
Apr 5, 2009

Looking through all my Windows environmental variables (User and System) I can't see Java on it anywhere; Java is installed, though, and java -jar works fine. I admit it's hardly a solution, but have you encountered a system where Java is installed but a call to java doesn't work?

Tesseraction
Apr 5, 2009

Interesting, there's a java.exe in System32 but Cygwin can't find it at all, which I only noticed when trying to do a cmp to see if it was different from the one installed in Program Files. Copying the sys32 file elsewhere allowed me to compare it as exactly identical, which suggests it's a symlink/junction. Anyway enough of that.

My point was really one of "shouldn't the easiest way just be calling 'java -jar'" with the idea being that if you get an error code then your .bat or whatever suggests getting Java? I guess it could be confusing if your jar returns failure exit codes too, so just compare. Having weirdly installed JREs muddies the waters a bit but then I don't know if this jar is aimed at technically competent people or the thoroughly green.

Tesseraction
Apr 5, 2009

Are those jars closed source? It could be the developer put stuff in to mess with decompilers, it could also be that Quiltflower seems to be specifically maintained by Minecraft modders. You might find it beneficial using other decompilers?

Tesseraction
Apr 5, 2009

hooah posted:

Does the class have a TA? Or have you talked to the professor at all? They should be able to help you at least wrap your brain around what the puzzle is asking. I've been coding for ~9 years (6 years professionally) and nothing comes to mind to me after 30 seconds, so this at least isn't trivial.

The puzzle is asking you to come up with all possible configurations of adding 1 or 2 to make 11. The point of making it recursive is to make it so that the 11 is arbitrary, so you can't hard-code the solution after working it out by hand.

Tesseraction
Apr 5, 2009

Hippie Hedgehog posted:

Is it just me or does this problem not really make a very convincing case for lambda functions?

I mean, they want to teach you how to use them, sure, but I hope there’s a future problem to teach you /when/ to use them.

It could be the bullshit hard question in the homework where most aren't expected to succeed but the teacher wants to see how they try (and likely fail) to solve it.

Tesseraction
Apr 5, 2009

RandomBlue posted:

Just telling them the answer isn't going to help them understand lambdas.

Oh absolutely - when I say bullshit hard I don't mean that the teacher shouldn't set them, it's that the student is right to find it bullshit hard, and learn from what they couldn't manage to achieve. Sometimes you learn more from failing than you do from succeeding.

Tesseraction
Apr 5, 2009

They should be interchangeable as both are subclasses of AbstractMap.

Tesseraction
Apr 5, 2009

How are you invoking the program / specifying the input file? It looks like main is opening it and looking for the file specified as a single argument, however in process(File file) you've hard-coded the Bill of Rights.

Is BillofRights.txt in your classpath? You should be able to drag and drop it into your IDE to help with getting it linked correctly.

Additionally where is DICTIONARY_FILE aka dictionary.txt?

Tesseraction
Apr 5, 2009

Can you post the text of the Exception? It should have the name of the .java file you've got plus its line numbers - if you could also supply those line numbers we can figure out where the error is happening.

edit, picking out a screenshot I posted in this thread a decade ago :corsair: you should have something like this:

Tesseraction
Apr 5, 2009

Open the Run settings (Run -> Run... in Eclipse as I remember it) and go to Java Application -> Main -> Arguments -> Program arguments and put in

./BillofRights.txt

Tesseraction
Apr 5, 2009

Should've known - if you go to the physical file structure where is BillofRights.txt relative to Main.java (or whatever you've called it)

I vaguely recall that it'll be like src/Main.java and then something like files/BillofRights.txt or maybe even just ./BillofRights, in which case the argument should be ../BillofRights.txt

Java shouldn't be arsey about / vs \ as long as you use them consistently.

Tesseraction
Apr 5, 2009

Threw that into Notepad++ to get the line number it's this line:
code:
    				wordToFrequencyMap.replace(input.next(), value++);
Been a while since I've used scanner but doesn't input.next() iterate with each call?

Try locally assigning input.next() to a variable.

code:
 private static void process(File file) throws FileNotFoundException {
    	Scanner input = new Scanner(new File("BillofRights.txt"));
    	while (input.hasNext()) {
                currentWord = input.next()
    		if (dictionaryWords.contains(currentWord)) {
    			if (wordToFrequencyMap.containsKey(currentWord)) {
    				Integer value = wordToFrequencyMap.get(currentWord);
    				wordToFrequencyMap.replace(currentWord, value++);
    			}
    			else {
    				wordToFrequencyMap.put(currentWord, 1);
    			}
    		}
    		else {
    			misspelledWords.add(currentWord);
    		}
    			
    	}
    	
    }

Tesseraction
Apr 5, 2009

I believe your teacher granted a hint with this:

code:
private static final Map<Integer, String> frequencyToWordMap = new TreeMap<>(Collections.reverseOrder());
All Maps can provide a collection: https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Collection.html

Tesseraction
Apr 5, 2009

Ah good, I still have Eclipse installed. You keep trying to work your way around collections and I'll play around with them too and refresh my memory. With any luck you won't need my help.

Tesseraction
Apr 5, 2009

Yes, looking back at it, is the idea that the output for that part is that if the words "the" "bill" and "rights" appear 100, 200 and 150 times respectively, you get this output:

200: bill
150: rights
100: the

?

Tesseraction
Apr 5, 2009

And what does it do if two words appear at the same frequency?

Tesseraction
Apr 5, 2009

Right, so your teacher gave you a better hint:

code:
         frequencyToWordMap.forEach((k, v) -> {
            System.out.println(k + ": " + v);
        });
Which shows that Maps have a forEach function that effectively iterates over the map. Remember too that frequencyToWordMap was explicitly constructed to store things in reverse order:

code:
private static final Map<Integer, String> frequencyToWordMap = new TreeMap<>(Collections.reverseOrder());
This should be enough to get your assignment done.

Oh, but a fair warning. value++ and ++value have different effects - something I picked up on while copying your code. ;)

Tesseraction
Apr 5, 2009

Yeah I'm not sure why they both exist except the teacher testing what the student does.

Tesseraction
Apr 5, 2009

Think about how you incremented the count, and how you can do something similar with a string.

Tesseraction
Apr 5, 2009

No, but think about the mechanism of addition.

You write value++ but that's just a shorthand for value + 1

Adbot
ADBOT LOVES YOU

Tesseraction
Apr 5, 2009

You're using:
String word = k;

But you need another way of doing this.

You're no longer using a Scanner, so you need to think about where you're getting the value of what is potentially being added vs. what has already been added.

Remember what a Map lets you do.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply