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
Jo
Jan 24, 2005

:allears:
Soiled Meat

Zaphod42 posted:

The problem is that you're extending Application in the last one, not the others. That's creating a new thread, which then invokes the start method. But you've also got a main method? I'm pretty sure that's wrong, and that's what's causing all your issues.

In my defense, ALL of the JavaFX examples have main inside the main Application. This is how Oracle says to do it (http://docs.oracle.com/javase/8/javafx/get-started-tutorial/hello_world.htm).

No matter the case, it still doesn't work after I remove main:

code:
import javafx.scene.image.Image;

public class Main {
	public static void main(String[] args) {
		Image image = new Image("file:test.png");
	}
}
Stack trace:
code:
Exception in thread "main" java.lang.RuntimeException: Internal graphics not initialized yet
	at com.sun.glass.ui.Screen.getScreens(Screen.java:70)
	at com.sun.javafx.tk.quantum.QuantumToolkit.getScreens(QuantumToolkit.java:699)
	at com.sun.javafx.tk.quantum.QuantumToolkit.getMaxPixelScale(QuantumToolkit.java:714)
	at com.sun.javafx.tk.quantum.QuantumToolkit.loadImage(QuantumToolkit.java:722)
	at javafx.scene.image.Image.loadImage(Image.java:1046)
	at javafx.scene.image.Image.initialize(Image.java:795)
	at javafx.scene.image.Image.<init>(Image.java:609)
	at com.josephcatrambone.sharpcloud.Main.main(Main.java:12)

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Jo posted:

In my defense, ALL of the JavaFX examples have main inside the main Application. This is how Oracle says to do it (http://docs.oracle.com/javase/8/javafx/get-started-tutorial/hello_world.htm).

No, you're misunderstanding. Its not just a matter of having main inside application. Its a matter of having the code that handles image manipulation INSIDE the main(). You can't do that. You can have a main inside it or external to it, or not even have one at all. Sorry if I was confusing by saying that. You don't need main at all with an application class, you can invoke it as an application and java knows what to call or there's a default main() or whatever.

But you have to do the javafx calls from inside the javafx thread if you're starting an application, not from within your main. You have to invoke the application and let it call start() on its own, and THEN you're allowed to do image manipulation.

Following that link shows the following code

code:
package helloworld;
 
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class HelloWorld extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
 
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);

 Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 public static void main(String[] args) {
        launch(args);
    }
}
So its not happening in the main() method. Everything happens in Start(). See?

When I google "javafx image manipulation" I get:

https://docs.oracle.com/javafx/2/image_ops/jfxpub-image_ops.htm

Which has several examples, all of which have the code in the start() method and have the main method invoke the application, exactly like I told you to do. None of them do image manipulation IN the main() method.

Zaphod42 fucked around with this message at 22:31 on Sep 3, 2015

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Jo posted:

No matter the case, it still doesn't work after I remove main:

code:
import javafx.scene.image.Image;

public class Main {
	public static void main(String[] args) {
		Image image = new Image("file:test.png");
	}
}
Stack trace:
code:
Exception in thread "main" java.lang.RuntimeException: Internal graphics not initialized yet
	at com.sun.glass.ui.Screen.getScreens(Screen.java:70)
	at com.sun.javafx.tk.quantum.QuantumToolkit.getScreens(QuantumToolkit.java:699)
	at com.sun.javafx.tk.quantum.QuantumToolkit.getMaxPixelScale(QuantumToolkit.java:714)
	at com.sun.javafx.tk.quantum.QuantumToolkit.loadImage(QuantumToolkit.java:722)
	at javafx.scene.image.Image.loadImage(Image.java:1046)
	at javafx.scene.image.Image.initialize(Image.java:795)
	at javafx.scene.image.Image.<init>(Image.java:609)
	at com.josephcatrambone.sharpcloud.Main.main(Main.java:12)

What? Didn't you say on the last page that this worked fine for you?

code:
public static void main(String[] args) {
		//launch(args);

		Image img = Image("file:" + filename);
	}
Also you still have a main class, so did you mean to say you removed the extends Application instead?
In which case that's my bad, looks like you have to have an application to invoke JavaFX methods, hence the graphics not initialized problem.

If you're trying to run it without any GUI, then just do exactly like what Volguus posted. Or use a simpler image manipulation library and not a full window graphics library, yeah. But then you probably don't need JavaFX.

You said before you kinda wanted it with GUI sometimes but not with GUI other times?

Zaphod42 fucked around with this message at 22:33 on Sep 3, 2015

Jo
Jan 24, 2005

:allears:
Soiled Meat

Zaphod42 posted:

What? Didn't you say on the last page that this worked fine for you?

code:
public static void main(String[] args) {
		//launch(args);

		Image img = Image("file:" + filename);
	}
Also you still have a main class, so did you mean to say you removed the extends Application instead?
In which case that's my bad, looks like you have to have an application to invoke JavaFX methods, hence the graphics not initialized problem.

If you're trying to run it without any GUI, then just do exactly like what Volguus posted. Or use a simpler image manipulation library and not a full window graphics library, yeah. But then you probably don't need JavaFX.

You said before you kinda wanted it with GUI sometimes but not with GUI other times?

Emphasis mine.

Yes. I had to remove just the extends Application part to get a new exception. With extends Application I get a GUI (or an exception if I'm on a headless box), and it automatically spawns the GUI even if I do it outside of start(). Without extends Application I get the exception above. Unfortunately, It turns out it's not possible to use JavaFX Image without a GUI, as I found just now: https://bugs.openjdk.java.net/browse/JDK-8093075

Looks like if I want a headless and GUI application I have to use two different Image classes. :(

EDIT: Thank you both for the input, though. Wish the outcome could have been better.

EDIT EDIT: \/\/ :doh:

Jo fucked around with this message at 22:59 on Sep 3, 2015

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Jo posted:

Emphasis mine.

The example above that had main() inside the MainWindow which extended Application. I removed the extends Application part. It turns out it's not possible to use JavaFX Image without a GUI, as I found just now: https://bugs.openjdk.java.net/browse/JDK-8093075

Looks like if I want a headless and GUI application I have to use two different Image classes. :(

EDIT: Thank you both for the input, though.

Yeah that's pretty much exactly what I said in my last post :cheeky:

Easiest would probably be to have a image manipulation class using some library that just does the image manipulation, then if you want headless you just invoke those from command line and if you want GUI then you can create a JavaFX application (or a Swing window or whatever) and then call the image manipulation class from there.

Its a little messy since you're using two different libraries but with each class only using one or the other that's pretty simple, and then you're still using the same exact image manipulation code in both the headless and GUI implementations so you don't have to worry about fixing something twice or the results being different.

ROFLburger
Jan 12, 2006

How can I have an appender write to a file as well as stdout?

Write now I've got two appenders logging to different files, but I'd also like to see their output in stdout

code:
log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.ButtLog=org.apache.log4j.FileAppender
log4j.appender.ButtLog.File=C:\\ButtLog.log
log4j.appender.ButtLog.layout=org.apache.log4j.PatternLayout
log4j.appender.ButtLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.DongLog=org.apache.log4j.FileAppender
log4j.appender.DongLog.File=C:\\DongLog.log
log4j.appender.DongLog.layout=org.apache.log4j.PatternLayout
log4j.appender.DongLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.ButtLogger=TRACE, ButtLog
log4j.additivity.ButtLogger=false

log4j.category.DongLogger=TRACE, DongLog
log4j.additivity.DongLogger=false
You can safely assume that I know nothing about log4j. I read over the docs but it wasn't immediately clear to me.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Additivity true

ROFLburger
Jan 12, 2006

thanks

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Yeah Log4j is the poo poo, it can do pretty much whatever you want.

Additivity true means when you call a log at that level, you also call the log on the parent levels above (and up until you hit additivity = false at some point or the root)

Additivity false means only trigger the one level.

ROFLburger
Jan 12, 2006

thanks for the explanation, that makes sense to me now

Data Graham
Dec 28, 2009

📈📊🍪😋



How I wish they cold come up with normal names for things, like "propagate" or something.

Volguus
Mar 3, 2009
Just FYI (not really that important), but log4j's successor is nowadays logback. I've been using logback in a fair amount of projects for a few years and is quite good. Haven't seen anything yet that it cannot do (plus it has slf4j integration out of the box), and it has once nice feature that I don't remember log4j having: by default it loads logback-test.xml for configuration, which makes it really handy for unit testing. Have logback.xml in the main/resources folder for normal running, and have logback-test.xml in test/resources to be loaded only for the unit tests. As for usage, via slf4j everything is just like before, not a line of code to change ....

MrMoo
Sep 14, 2000

Doesn't look very good compared to log4j2 though.

pepito sanchez
Apr 3, 2004
I'm not mexican
working with java7 and trying to call an anonymous function inside the main class to load test data. this is mostly just an experiment. first: how is this code below not working? nothing is loading, while if i were to call the load method normally from a separate java class from main there's no issue. second: when is it actually a good idea to use anonymous classes and functions like this? all i know is that the class is supposed to hide code a little better, and that the anonymous function is immediately called just once. i guess i should also ask if this is used at all in java 8, or what's the practice there? lambda functions look cool and i'll be playing with them soon.

code:
public class MainClass{

     class TestData {
            public void load(){
            new Object(){
                public void load(){
                     //getting my singleton instance here
                    Shop shop = Shop .getInstance();

                    shop .addSomething(new Genre("Tango"));
                    shop .addSomething(new Genre("Rock"));
                    shop .addSomething(new Genre("Salsa"));

                    shop .addSomething(new Singer("Carlos Gardel"));
                    shop .addSomething(new Singer("Rolling Stones"));
                    shop .addSomething(new Singer("Celia Cruz"));
                    shop .addSomething(new Singer("Various"));

                    }
                }
                    .load();
           }
        }
    public static void main(String[] args) {
        /*No idea what to do here. 
        I can't access the class above, and if i I put the class in main then 
        I get null pointer errors, because that's just wacky*/
        new Menu().setVisible(true);
    }
}
edit: tried a few things. making the inner class public, etc. stuff that shouldn't work isn't working(good!) but i'd like this cleared.

edit2: of course i figure it out in a few ... :(

code:
//in main
TestData t = new TestData ();
t.load();

//changed testdata class to static type
still would like answers for the rest!

pepito sanchez fucked around with this message at 20:07 on Sep 7, 2015

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
You typically wouldn't want to do something like this. If you want to remove a block of code from the flow of your function, you'd do that in a private method of the same class. If you needed it to be accessible by other classes, you could make an appropriately named class with public static methods. (This is sometimes considered an antipattern, but is frequently done anyway.)

Anonymous classes (and lambdas, in Java 8, which actually are anonymous classes) are mostly used when you have a method that accepts an interface, a need to call this method inline, and you don't want to bother creating a full class to do work. Ususally something like:

Java code:
List<Dog> dogs = getDogs();
Collections.sort(dogs, new Comparator<Dog>() {
    public int compare(Dog a, Dog b) {
        if (a.weight == b.weight) {
            return 0;
        } else if (a.weight > b.weight) {
            return 1;
        } else {
            return -1;
        }
    }
});

// do something with a list of dogs sorted by their weight
In Java 8, this becomes a bit less unweildy:
Java code:
List<Dog> dogs = getDogs();
Collections.sort(dogs, (a, b) -> {
    if (a.weight == b.weight) {
        return 0;
    } else if (a.weight > b.weight) {
        return 1;
    } else {
        return -1;
   }
});
It's doing the same thing - creating an anonymous Comparator<Dog> for the sort method. In Java 8, a lambda is allowed to take the place of an argument where the argument is an interface, and the interface only has one method. The compiler is then able to infer the Interface and types that you meant, and "fill in" the boilerplate.

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

Gravity Pike posted:

In Java 8, this becomes a bit less unwieldy:
Java code:
List<Dog> dogs = getDogs();
Collections.sort(dogs, (a, b) -> {
    if (a.weight == b.weight) {
        return 0;
    } else if (a.weight > b.weight) {
        return 1;
    } else {
        return -1;
   }
});

And how you'd actually write the above in Java 8:
Java code:
final List<Dog> dogs = getDogs();
dogs.sort(Comparator.comparing(Dog::getWeight));

pepito sanchez
Apr 3, 2004
I'm not mexican
thank you. it sucks because we're limited to using java 7. lambda expressions just seem very interesting, but i'll make do. i don't want to seem like i'm being fancy or clever for no real gain. i suppose a lot might come down to design decision and a need for these things.

geeves
Sep 16, 2004

The Laplace Demon posted:

And how you'd actually write the above in Java 8:
Java code:
final List<Dog> dogs = getDogs();
dogs.sort(Comparator.comparing(Dog::getWeight));

My company just upgraded to Java 7. Now I want them to upgrade to 8 because this involves a good portion of what I deal with.

emanresu tnuocca
Sep 2, 2011

by Athanatos
Is there anyway to do something like this:
code:
Public Class ParticleEmitter<T extends ParticleObject>{
     public void emitParticle(){
       K particle = new K();
    }
}
I thought it would be an elegant way to make some emitter that can emit particles of different types with ease but it looks like Java doesn't agree.

Just curious if there's a way to instantiate from a generic type like that.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

emanresu tnuocca posted:

Is there anyway to do something like this:
code:
Public Class ParticleEmitter<T extends ParticleObject>{
     public void emitParticle(){
       K particle = new K();
    }
}
I thought it would be an elegant way to make some emitter that can emit particles of different types with ease but it looks like Java doesn't agree.

Just curious if there's a way to instantiate from a generic type like that.

Is it because you wrote T in the declaration but K in the method?

e: Looks like it wouldn't work even if you did. From what I can see (like http://stackoverflow.com/a/1090488), you could pass the class object itself on construction and store it in your generic class, then call newInstance() on it when you need a new particle.

carry on then fucked around with this message at 16:48 on Sep 8, 2015

emanresu tnuocca
Sep 2, 2011

by Athanatos

carry on then posted:

Is it because you wrote T in the declaration but K in the method?

e: Looks like it wouldn't work even if you did. From what I can see (like http://stackoverflow.com/a/1090488), you could pass the class object itself on construction and store it in your generic class, then call newInstance() on it when you need a new particle.

Thanks. Well it looks like if I do that I'll only be able to use the default constructor. Which I guess could still work.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

emanresu tnuocca posted:

Thanks. Well it looks like if I do that I'll only be able to use the default constructor. Which I guess could still work.

You can use some fancy reflection shenanigans to do other constructors too, but it makes it harder to be generic.

class.getConstructor(String.class).newInstance("String Parameter");

Squashy Nipples
Aug 18, 2007

I've started helping out with a local high school robotics team, and I'd like to learn Java. Can anyone recommend some resources for someone starting out?

Most of the programming I've done has been in dead languages like FORTH and various BASICs. Currently, I use SQL and VBA regularly to perform data analysis for my job.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

The official Java trails are always recommended
https://docs.oracle.com/javase/tutorial/
Just go through them in order - you might want to skip Generics at first (and maybe Annotations) until you have a handle on Java in general, it's powerful but I found it pretty confusing when I was starting out. More professional people may disagree though!

Squashy Nipples
Aug 18, 2007

Perfect, thank you. I'm totally happy with dry, technical text.

When I googled around, I mostly found pay stuff.

ada shatan
Oct 20, 2004

that'll do pig, that'll do
You might want to check out Udemy for some of their free content on Java. They have been really good with a lot of their intro courses I have checked out.

HFX
Nov 29, 2004

baka kaba posted:

The official Java trails are always recommended
https://docs.oracle.com/javase/tutorial/
Just go through them in order - you might want to skip Generics at first (and maybe Annotations) until you have a handle on Java in general, it's powerful but I found it pretty confusing when I was starting out. More professional people may disagree though!

I agree with you. Generics are cool, but you should have a firm grasp on typing first. Annotations can be skipped for quite a while as it isn't until you get into frameworks were they start to shine.

Brain Candy
May 18, 2006

emanresu tnuocca posted:

Is there anyway to do something like this:
code:
Public Class ParticleEmitter<T extends ParticleObject>{
     public void emitParticle(){
       K particle = new K();
    }
}
I thought it would be an elegant way to make some emitter that can emit particles of different types with ease but it looks like Java doesn't agree.

Just curious if there's a way to instantiate from a generic type like that.

Java 8 lets you skip all the reflection, if you make ParticleEmitter an interface (or just use Supplier)
code:
ParticleEmitter<Kaon> emitter = Kaon::new;

Jocoserious
Jun 9, 2014

LOOK OVER HERE!!
I'm having trouble getting my program to loop properly. The "q" used for ending the input is staying in the buffer and interfering with the yes/no prompt. I'm relatively new to Java and programming in general, so is there some buffer clearing method I'm not aware of that would fix this? I apologize if my code is sloppy.

quote:

public static void main()
{
boolean again = true;
String answer = "y";

while(again){
int currentSize = 0;
int [] input = new int[10];
Scanner in = new Scanner(System.in);

System.out.println("Please enter values, q to quit:");

while (in.hasNextInt()){
if (currentSize < input.length)
{
input[currentSize] = in.nextInt();
currentSize++;
}
}

// a bunch of irrelevant method calls

System.out.println("\n\nTry it again(y/n)?");
String question = in.next();
if (question.equals(answer)){
again = true;
}
else{
again = false;
}
}

TheresaJayne
Jul 1, 2011

Jocoserious posted:

I'm having trouble getting my program to loop properly. The "q" used for ending the input is staying in the buffer and interfering with the yes/no prompt. I'm relatively new to Java and programming in general, so is there some buffer clearing method I'm not aware of that would fix this? I apologize if my code is sloppy.

then straight after the while(again) loop add a call to read in the q so that its clear for the y/n

Jocoserious
Jun 9, 2014

LOOK OVER HERE!!

TheresaJayne posted:

then straight after the while(again) loop add a call to read in the q so that its clear for the y/n

:cripes: Of course, can't believe I didn't think of that. Thanks.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
To expand on what TheresaJayne said,

whats happening is when you call while (in.hasNextInt()){} it keeps calling it while hasNextInt() is true.

When the cursor on the line gets to where the next letter would be q, hasNextInt() returns false, so you stop.

But the input reader is still on the same line, still with its cursor before the q. So next time you call read, it gives you q.

Just simply call in.next(); on its own after you finish the while loop, don't even bother to save the results as a variable. That way the reader cursor gets moved to the next line, and then when you call in.next(); again, you'll get something after the q.

A cleaner way to do it would be instead of reading character by character, get yourself a BufferedReader and read each line at a time from the console. Then you can break down the lines with string manipulation if you need to, but it makes it easier to keep track of where the cursor is; just deal with lines of text at a time. Nothing wrong per se about doing it the way you are though, for this application anyways.

Jocoserious
Jun 9, 2014

LOOK OVER HERE!!

Zaphod42 posted:

Just simply call in.next(); on its own after you finish the while loop

This is exactly what I did. It never occurred to me to read the next character just to get it out of the way. Thanks again for the explanation.

Modulo16
Feb 12, 2014

"Authorities say the phony Pope can be recognized by his high-top sneakers and incredibly foul mouth."

I making a Caesar Cipher for schoolwork, and I am trying to modify it to take lowercase letters, but my arithmetic seems to be failing me. The cipher subtracts 'A' in Unicode, and displays the number, however when I do this with 'a' I get an out of bounds exception, which only seems to happen when I have a space. Why?

code:
import java.util.Scanner;



public class CeaserCipher	
{	
	protected char[] encoder = new char[53];
	protected char[] decoder = new char[53];
	
	public CeaserCipher(int rotation){
			
			for(int k = 0; k < 26; k++){
				encoder[k]=(char)('A'+(k +rotation)%26);
				decoder[k]=(char)('A'+(k- rotation + 26)%26);
                                
			}
                        for(int k=27; k < 52; k++){
                            encoder[k]=(char)('a' +(k + rotation) % 26);
                            decoder[k]=(char)('a' +(k - rotation + 26)% 26);
                        }
                        
                   
		}
	
	public String encrypt(String message){
		return transform(message, encoder);
	}
	
	public String decrypt(String secret){
		return transform(secret, decoder);
	}
	
	private String transform(String original, char[] code){
		char[] msg = original.toCharArray();
		for(int k=0; k < msg.length; k++)
			if(Character.isUpperCase(msg[k])){
				int j = msg[k] - 'A';
				msg[k] = code[j];
			}
                        else{
                            int j = msg[k] - 'A';
                            msg[k] = code[j];
                        }
                        
		return new String(msg);
	}
	public static void main (String[] args){
		CeaserCipher cipher = new CeaserCipher(3);
		System.out.println("Encryption code = " + new String(cipher.encoder));
		System.out.println("Decryption code = " + new String(cipher.decoder));
		System.out.println("Please Enter Your Secret Message: \n");
                Scanner input_message = new Scanner(System.in);
                String message;
                message = input_message.nextLine();
                String coded = cipher.encrypt(message);
		System.out.println("Secret:  " + coded);
		String answer = cipher.decrypt(coded);
		System.out.println("Message:  " + answer);
	}
}

emanresu tnuocca
Sep 2, 2011

by Athanatos
I am probably missing point but why not just use Character.touppercase() ?

Modulo16
Feb 12, 2014

"Authorities say the phony Pope can be recognized by his high-top sneakers and incredibly foul mouth."

emanresu tnuocca posted:

I am probably missing point but why not just use Character.touppercase() ?

I can try it, the thought never occured to me.

EDIT: This works but I would prefer to know why my code wont work.

Modulo16 fucked around with this message at 18:57 on Sep 15, 2015

emanresu tnuocca
Sep 2, 2011

by Athanatos
Uhm yeah I was also a little confused but looking at the table: http://unicode-table.com/en/

Unicode A = '65', unicode 'a' - '97', the difference is 32, so 'a' - 'A' != 'A', looks like you need to do 'smallCaps' - 32 = 'largeCap'.

Edit: ('SmallCharacter' - (a - A)) = LargeCaps

Edit: yeah this works
code:
		
	StringBuilder builder = new StringBuilder();
	String str = "abcdefghijklmnopqrstuvw_123_ABCDEFGHIJKLMNOPQRSTUV";
	System.out.println("Original string: " + str);
	for(char ch : str.toCharArray()){
		if(ch >= 'a' && ch <= 'z'){
			builder.append((char) (ch - ('a' - 'A')));
		}else{
			builder.append(ch);
		}
	}
	System.out.println("modified string: " + builder.toString());

emanresu tnuocca fucked around with this message at 19:35 on Sep 15, 2015

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

^^^ That's an issue for reals, but also:

Frank Viola posted:

I making a Caesar Cipher for schoolwork, and I am trying to modify it to take lowercase letters, but my arithmetic seems to be failing me. The cipher subtracts 'A' in Unicode, and displays the number, however when I do this with 'a' I get an out of bounds exception, which only seems to happen when I have a space. Why?

Your error message should tell you exactly which line it's failing on, and the type of Exception you get is a clue too. I'm guessing it's an ArrayOutOFBoundsException, and that means you're trying to access an index that's either bigger than the array, or less than zero.

You say you get this problem when there's a space in your message (right?). Have a look through your cipher code and work out what happens when you get to a space in your message - work out the numbers and the result you get.

I'm not sure why it would only fail when you add 'a' - doesn't it fail if you run it what you posted, where you subtract 'A' whether it's uppercase or not?

Modulo16
Feb 12, 2014

"Authorities say the phony Pope can be recognized by his high-top sneakers and incredibly foul mouth."

baka kaba posted:

^^^ That's an issue for reals, but also:


Your error message should tell you exactly which line it's failing on, and the type of Exception you get is a clue too. I'm guessing it's an ArrayOutOFBoundsException, and that means you're trying to access an index that's either bigger than the array, or less than zero.

You say you get this problem when there's a space in your message (right?). Have a look through your cipher code and work out what happens when you get to a space in your message - work out the numbers and the result you get.

I'm not sure why it would only fail when you add 'a' - doesn't it fail if you run it what you posted, where you subtract 'A' whether it's uppercase or not?

This was no help, I already know that it has to do with the array. I'm looking for the exact point that the code causes out of bounds and why it doesn't execute properly. It executed fine with all caps. I don't need to know where to look I need to know why the code I am using isn;t working, and why it specifically wont work, not some clue as to what to do.

Modulo16 fucked around with this message at 20:22 on Sep 15, 2015

Adbot
ADBOT LOVES YOU

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Frank Viola posted:

This was no help

Ok fine

Java code:
int j = msg[k] - 'A';
msg[k] = code[j];
A space has a codepoint of 32 and A is 65. What array index are you trying to access when msg[k]=" "

isUpperCase(" ") is always false so you always hit the else part with a space

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