/r/javahelp

Photograph via snooOG

General subreddit for helping with Java code.


General subreddit for helping with Java code.

Message the mods if you have suggestions.



Java Discord server (unofficial)


Learning Java

Please head over to /r/learnjava and read the sidebar there.

The best free Java tutorials are:

Use the MOOC as main course and Java for Complete Beginners as secondary resource.

Don't forget the Official Oracle Java Tutorials and the Official Java Documentation as they are extremely valuable resources.


Where should I download Java?

With the introduction of the new release cadence, many have asked where they should download Java, and if it is still free. To be clear, YES — Java is still free.

If you would like to download Java for free, you can get OpenJDK builds from the following vendors, among others:

Some vendors will be supporting releases for longer than six months. If you have any questions, please do not hesitate to ask them!


Posting rules

  1. DO NOT DELETE your posts once they are solved!

  • Use the "Solved" flair instead. This allows others to learn, too, and makes the helpers' efforts more effective.
  • No illegal/pirated content!

    • Anybody asking for or posting links to or suggesting to search for illegal/pirated content will be permanently banned without further warning!
  • No "Do my homework" posts!

    • Do not ask for complete solutions. We are here to help but not to /r/domyhomework. You do the work, and we help you. So - what have you tried?
    • For complete solutions, use a search engine instead. stackoverflow.com has a rich library of complete Java answers.
  • Describe the problem and what you want to achieve.

    • You get better tips if the readers know what you ultimately want to achieve, tips you didn't expect.
    • And in regards to describing your problem: "..., but it doesn't work." is insufficient! Do not expect people to put your code into their IDEs just to find out how the problem expresses itself.
    • If applicable, include the full error message or exception text!
  • Do not ask for or reply with solutions or keys to solutions.

    • Rather comment explanations and guides. Comments with solutions will be removed and commenters will automatically be banned for a week.
  • Use the search function.

    • Search for similar problems before posting.
  • No offers/requests to/for help via PM, Discord, Skype, etc.

    • Post your questions here so that other people can learn as well.
  • Post titles must be descriptive.

    • Bad title: "I'm new to Java and need help."
    • Good title: "How can I sort values without loops?"
    • The title should not describe your problem in full - that's what the post body is for.
    • No links in the titles - they are not clickable.
    • Nothing is "URGENT", nor "ASAP" - if you have waited too long, this is your problem, not ours. Such posts will be removed without warning.
  • No promises of rewards of any kind!

    • This includes both solicitation of services from those providing help and offers to pay from those requesting help.
    • Any post or comment that mentions payment may be subject to immediate ban from the subreddit.
  • Don't be a Jerk!

    • Don't insult, threaten, mock or harass other users. Please, maintain proper language.
    • We don't tolerate foul language for any reason. Any violation will result in an immediate thinking period ban of at least 4 days. Second offence will result in a permanent ban.
  • No JavaScript, Android, Minecraft or Processing!

  • No links to your stackoverflow questions.

    • We are not a second opinion to stackoverflow, nor are you going to get answers here when you didn't get satisfying ones there.
  • Format your code.

    • Please, properly format your code. This includes proper indentation. There are guidelines on how to format code in the sidebar in both, abridged form directly in the sidebar and in long form in the linked post.
    • For small bits of code (less than 50 lines in total, single classes only), use Reddit directly (one blank line, then 4 spaces before each line).
    • Otherwise: The sidebar has no-login links that even support syntax highlighting!
  • No screenshots of code!

    • You can add a screenshot of your IDE if it is relevant, but regarding the code itself, you must provide it in text form and properly formatted (and, please, properly indented).
  • No AI generated content!

    • We explicitly forbid any form of AI generated content. Posting any AI content results in an instant, permanent, and irrevocable ban without warning.
    • Code posting
    • Do not submit executable jar or compressed (zip, rar, 7z, etc.) files!
    • For small bits of code (less than 50 lines in total, single classes only), the default code formatter is fine (one blank line, then 4 spaces before each line).
    • Pastebin for programs that consist of a single class only
    • Gist for multi-class programs, or programs that require additional files
    • Github or Bitbucket repositories are also perfectly fine as are other dedicated source code hosting sites.
    • Ideone for executable code snippets that use only the console
    • Repl.it - online IDE for many different programming languages
    • Browxy - online IDE for several programming languages
    • Google Drive, Dropbox, Mediafire, etc. are not suitable for code posting!
  • Check out the wiki for frequently asked questions. Please feel free to contribute!

  • Sort by: Unsolved Solved Codeless Advent Of Code

    /r/javahelp

    94,432 Subscribers

    1

    Accidentaly sent the wrong file during a test, and now my teacher won't accept the original, because I could have faked it

    How can I prove that it was made during the test - IntelliJ

    2 Comments
    2024/05/17
    07:59 UTC

    1

    Javalin: Setting up a HTTPS Server

    Hey Guys,

    so i'm figuring out how javalin works for a projekt of mine.
    But i can't get the https Server running, with an simple http Version it works but that's not secur enough.
    So i can't use the server() Method (idk why) and i don't know how to do it differently cause that's how it is in the documentations. I would appreciate a lil help, thank yoouuuuuuu.

    package bestellsystem;
    
    import io.javalin.Javalin;
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.server.ServerConnector;
    import org.eclipse.jetty.util.ssl.SslContextFactory;
    
    public class Main {
    
        public static void main(String[] args) {
            // SSL Context Factory
            SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
            sslContextFactory.setKeyStorePath("keystore.jks");
            sslContextFactory.setKeyStorePassword("password");
            sslContextFactory.setKeyManagerPassword("password");
    
            // Jetty Server
            Server server = new Server();
            ServerConnector sslConnector = new ServerConnector(server, sslContextFactory);
            sslConnector.setPort(8443);
            server.addConnector(sslConnector);
    
            // Javalin App
            Javalin app = Javalin.create(config -> {
                config.server(() -> server);
            }).start();
    
            app.get("/", ctx -> ctx.result("Hello, HTTPS World!"));
        }
    }
    
    1 Comment
    2024/05/17
    06:36 UTC

    1

    JFrame layers

    i cant figure out how to put this blue box on top of the label i have. please be specific i am new to java. no err messages but i don't get a blue box in the top right.

    hear is the code --->

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Frame;
    import javax.swing.BorderFactory;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.Border;
    public class main {
    public static void main(String\[\] args) {
    //make the frame  
    
    JFrame frame = new JFrame(); //creat window/gui  
    
    frame.setTitle("the window of doom"); // give the window a name  
    
    frame.setDefaultCloseOperation(JFrame.EXIT\\\_ON\\\_CLOSE);// X button works now  
    
    frame.setExtendedState(Frame.MAXIMIZED\\\_BOTH);  
    
    frame.setVisible(true);//make the window/gui visable to the user  
    
      
    
      
    
    
    
      
    
      
    
    //make the lable  
    
    JLabel lable = new JLabel();//make lable  
    
    lable.setText("Welcome!");//set text of lable  
    
    frame.add(lable);  
    
      
    
    //make a image  
    
    ImageIcon image = new ImageIcon("other orange frog.png");  
    
    Border border = BorderFactory.createLineBorder(Color.red, 3);  
    
    lable.setIcon(image);  
    
    lable.setHorizontalTextPosition(0);//aline  
    
    lable.setVerticalTextPosition(1);//aline  
    
    lable.setForeground(Color.orange);//set color  
    
    lable.setFont(new Font("MV Boli", Font.PLAIN, 100));//set font  
    
    lable.setIconTextGap(25);// set gap of text according to image  
    
    lable.setBackground(Color.red);//background color  
    
    lable.setOpaque(true);//display background color  
    
    lable.setBorder(border);  
    
    lable.setVerticalAlignment(JLabel.CENTER);  
    
    lable.setHorizontalAlignment(JLabel.CENTER);  
    
    lable.setBounds(230, 200, 0, 200);  
    
      
    
      
    
    JPanel gamePanel = new JPanel();  
    
    gamePanel.setBackground(Color.blue);  
    
    gamePanel.setBounds(100, 100, 0, 0);  
    
    gamePanel.setBorder(border);  
    
    frame.add(gamePanel);  
    }
    }
    7 Comments
    2024/05/17
    03:35 UTC

    2

    Problem with Java program execution (beginner )

    I am simply running a "hello world" program and when I'm using code runner extension, I'm getting this in terminal

    $ cd "c:\Users\chait\Desktop\java\" && javac hello.java && java hello
    >

    it's going into input mode showing '>' but not giving the output.
    When i manually run
    "javac hello.java && java hello"
    then it's working.
    $ javac hello.java && java hello
    ==Hello=====Guys==

    I'd really appreciate if anyone can help me out on this one.
    I even set the environment variables for the java/.../bin

    Update: When I changed the default terminal to Powershell from gitbash it working fine. But I'd still like to use git bash so the problem is still there

    5 Comments
    2024/05/17
    03:16 UTC

    2

    Please roast my JMH-based interpreter dispatch benchmark

    Hi, I ponder implementing a scripting language in Java and vaguely remember some disagreement about the difference in performance of AST walkers vs bytecode interpreters. Unable to find a benchmark I created a simple benchmark with a bunch of types of dispatch in order to look for extreme differences.

    Results so far:

    1. AST walker and stack-based bytecode VM share the 3rd place
    2. walking a register-based graph is about 50% faster than 1.
    3. register-based bytecode VM is about 3x faster than 1.

    Link to repository

    Thoughts? Did I make any mistakes regarding JMH? Do you get similar numbers?

    1 Comment
    2024/05/16
    21:34 UTC

    2

    Backend (Java/Spring) developer using Mulesoft: what does this mean exactly?

    Hi guys, I'm a student trying to start an internship. I've this opportunity to work in a locally well-known consulting company, they told me they're trying to find a back-end developer and say they're interested in my profile because I know Java and Spring basics.

    Nothing wrong up to now, until they told me that they use extensively a low-code tool called Mulesoft to do integration. And they said that I'd be expected to know how to use this tool well.

    I got a bit panicked by this. I had never heard of it, and googled and found out lots of people saying that this isn't a good career choice as it's low-code and work experience with it is mostly seen as useless to become a software developer that actually writes codes. And having that on my resume will only hurt my chances of being employed as a developer.

    Today I emailed the HR again, and they said that they're looking for a backend developer who will be trained on Mulesoft and Java/Spring, and that they're looking for a mixed profile who will do both.

    However, I still don't get it. What does it mean exactly? Does someone here have experience with this thing? I'm scared that they're looking for an integrator/consultant/Specialist who will mostly just use Mulesoft and write very little code. And I'm also scared that I'll be only a consultant to solve their clients' issues related to Mulesoft, so that I'll be pigeonholed into a Mulesoft specialist. That's not what I want.

    Also, I've a friend of mine who got promised to do programming at the interview, so he accepted the offer, but then he got forced to learn a low-code platform, without coding a single line. So he resigned and he's looking for an internship again now. I'm scared that this company is doing the same to me, promising me to do back-end/coding, but if I accept the offer I'll be forced to learn exclusively Mulesoft. Is this possible?

    But I'm fine if I'll be mainly writing code and just use that for API integration, so I'm ok if it's just a minor part of the job. This way, most the skills I learn will still be very transferable.

    Can someone help me out? Thanks!

    14 Comments
    2024/05/16
    21:27 UTC

    2

    springboot3 use jpa to create entity with @Id added to the Primary key id but got Error Persistent entity 'Article' should have primary key

    @Data
    @Entity
    public class Article {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;  //primary key
        @NotEmpty
        @Pattern(regexp = "^\\S{1,40}$")
        private String title; //title
        @NotEmpty
        private String content;  // content
        @NotEmpty
        @URL
        private String coverImg;  //cover_img
        @State
        private String state; //state published|draft
        @NotNull
        private String categoryId;  //category_id
        private Integer createUser; //create_user
        private LocalDateTime createTime;  //create_time
        private LocalDateTime updateTime; //update_time
    }

    When i try to run the main method to let JPA automatically generates mapping relationships, errors:

    Entity 'com.iota.pojo.Article' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)

    3 Comments
    2024/05/16
    13:39 UTC

    3

    Scheduling jobs in Java Spring best practices/approach

    Hi!

    I'm an absolute beginner Java developer. This is my first job and I've only started 2 months ago. Currently I don't have a senior developer that I can consult with on the project and I'm kind of clueless where to go.

    Here is my problem:

    I need to run some tasks every day at midnight. Let's called it MidnightJob. It's basically just reading huge amounts of data from a database, execute some logic and then rewrite them back to the database. There is also another job that needs to be executed if and only if that previous job has run successfully. Let's call it FinalJob. If the MidnightJob didn't run successfully then it needs to be rerun and only proceed with FinalJob when they are successful. I also need to store information about the Jobs themselves e.g. when did they start executing? When did they finish? Did they even finish at all or was there some sort of error during the execution.

    What would be the best way to go about this? I was looking into Sping Batch but it seems pretty complex so I would need quite some time to learn how it works and set up something functional with it. I have managed to make the MidnightJob part function okay-ish albeit mine is a pretty naive solution and doesn't accoutn properly for database outages, failures as I'm not 100% sure how to solve the issue of retrying job executions. I was wondering if there was a different solution or framework that I don't know about. Any help would be appreciated.

    Thank you for reading!

    5 Comments
    2024/05/16
    13:37 UTC

    2

    Query regarding deployment of program

    In our java program/project, we are using 'jdatechooser' component. So, when we are deploying our project in 'launch4j' the exception is showing error that it is 'unable to initialize main class jdatechooser.jdatechooseing' which is further caused by 'jdatechooser' Is there any solution so that our program can be deployed. Any suggestions will be very helpful. Thankyou :)

    2 Comments
    2024/05/16
    06:29 UTC

    3

    Class Data Sharing

    I am about two months into Java, so I'm definitely still learning a lot everyday.

    We are working on an application where startup time for a JVM is extremely slow.

    I tried Class Data Sharing (CDS), using this: Class Data Sharing in Java - GeeksforGeeks. But I gained no noticeable improvements. Maybe 40 second load-up time down to 39 seconds. When I create the Shared Archive, I notice many of the classes from the Jython library could not be Archived because they are pre-JDK-6, which CDS does not support.

    So I tried just doing core Java classes with a simple Xshare:dump. But that wasn't gaining any performance either. In fact, I am not seeing any gain in performance with Xshare:auto vs Xshare:off. Has anyone else tried CDS but not seen any gain in performance?

    9 Comments
    2024/05/16
    04:32 UTC

    2

    Multiple group chats using sockets

    I’m new to Java (and to programming overall) and I’ve been trying to create an instant messaging program where multiple clients can connect to different group chats and message only the clients in those group chats.

    I’ve been working on this for about a month and I’ve managed to create a single chat room that multiple clients can join and chat in but when it comes to creating multiple chat rooms I’m stumped (bordering desperate)!

    I tried using a hashmap to store where the clients were and then used a for loop to send messages to relevant clients. This became too messy though and ended up not working. I also looked into MultiCastSockets but I just ended up not being able to make multiple chat rooms there either. I feel like nio channels are my best bet but I haven’t been able to find a guide that has made me understand. Plus the way I’m thinking now I would probably use the channels to create multiple chat rooms within a clients thread (each client has a thread which is what lets me have multiple clients at once) but then I wouldn’t know how to get the other clients to access this specific channel.

    If anyone can give me any tips on how to do this, or point me in the direction of where I can read up on this I’d be really grateful!

    3 Comments
    2024/05/15
    23:47 UTC

    1

    Java Topics Suggestion (.NET to Java)

    I've been working with .NET/Core for the past 12 years. I now have an offer for a Java role starting in 2 weeks. I've used Java/JSP/Servet but that was more that a decade before switching to .NET.

    I will appreciate any suggestions or advise on Java topics to review. I have so far reviewed and pretty much understand Java collections, Lambda/Functional Interfaces and Streams through courses on O'Reilly.

    3 Comments
    2024/05/15
    22:54 UTC

    3

    How to show my family what I'm learning at school?

    I just started learning how to code, and I want to show my mum and sister some of the dumb stuff I have wrote. (I wrote something that asks you some questions and then tells you wether or not you're ready to party, and your predicted party awesomeness score, and one that is basically just a madlibs)

    How can I send them what I wrote in a way that they can run it and interact with it? they both have macs, and are not tech saavy at all, so ideally nothing that would require them to download a program. They don't need to be able to see the code either, just input the stuff when it prompts.

    I just finished my first week at school and tried asking my teacher but she didn't really understand the question. She doesn't speak English very well so although shes been great at showing us how to write code, she hasn't been able to really explain what the different aspects of coding ARE, so apologies for maybe not explaining this great.

    TL;DR I have two .java files and want to send them to someone to run without them needing to download a program.

    9 Comments
    2024/05/15
    22:53 UTC

    1

    WebLogic help needed

    I’m working on a project where some of the software is older than me. And currently I’m trying to solve an issue that I just don’t have the expertise needed.

    So we are migrating this application to WebLogic 14 (if I could, I would avoid WebLogic at all costs but we are where we are). There is a client application that is making a call to the WebLogic EJB that does some other calls, some processing and returns back the data to the client. Overall it works just fine. But under a heavier load users complain about slow response times.

    The network tracing shows that the servers (we have a managed cluster of about 60 servers) received the request. But under heavy load, it takes up to 30 seconds for the EJB to actually start processing request. The CPU and memory utilisation for the servers seem fine. Whoever set up the whole cluster might have been clueless so there are a lot of default settings left.

    I’ve looked into various things that could slow down the processing the requests but I can’t seem to identify what’s causing these issues.

    Any ideas where to start looking/how to prove what’s actually causing the delay?

    5 Comments
    2024/05/15
    20:48 UTC

    1

    De-lagging Swing Resize?

    I was contemplating creating a UI in Java Swing since the API looked pretty nice. However the initial impression regarding responsiveness was not great. In particular components lag way more than acceptable when a window is resized and the components need to rescale.

    Do you have any tips to share on how to make the UI responsive?

    Here is a recording showing just how laggy the simplest application is, and below that the source for the app.

    import java.util.Arrays;
    import java.util.List;
    import javax.swing.*;
    
    class TestWindow {
        public static void main(String[] args) throws Exception {
            var keys = Arrays.asList("java.vm.name", "java.vm.version", "java.vm.vendor", "java.vendor.version");
            List<String> lines = keys.stream().map(k -> String.format("%-20s: %s", k, System.getProperty(k))).toList();
    
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.invokeLater(() -> {
                JFrame frame = new JFrame("Test");
                frame.add(new JTextArea(String.join("\n", lines)));
                frame.pack();
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setVisible(true);
            });
        }
    }
    14 Comments
    2024/05/15
    18:45 UTC

    2

    Spring Data JPA returns one row for return type BookRecord[] and multiple rows for return type List<BookRecord>.

    So this query will return only one record(row from db):
    1.@Query("SELECT new com.example.BookRecord(b.title, b.author) FROM Book b")
    BookRecord[] findAllBooks();

    This query will return all rows from db:

    2.@Query("SELECT new com.example.BookRecord(b.title, b.author) FROM Book b")
    List<BookRecord> findAllBooks();

    Interesting twist, this query will return all rows like 2. query:

    3.@Query("SELECT new com.example.BookRecord(b.title, b.author) FROM Book b")
    Object[] findAllBooks();

    BookRecord:

    public record BookRecord(String title, String author) { }public record BookRecord(String title, String author) { }
    3 Comments
    2024/05/15
    11:23 UTC

    0

    Java Software Developer Intern

    Hey guys, Right now I'm chasing Java Software Engineer Intern position, and I'm on test phase now, where I should write test to get to Interview, so do you have any advice what should I except in test or what should I focus as Intern? I was Junior QA Engineer and I am switching as java developer so, what should I study?

    1 Comment
    2024/05/15
    08:21 UTC

    2

    Better / idiomatic solution for tasks results when using virtual threads

    Was demoing the use of virtual threads in a quick project and a couple of questions came up. Wanted to get some opinions:

    • Is .resultNow the better way to get the value of a Future? For example, if using an ExecutorService, I'd have to use it after closing it or using a try-with-resources.
    • What would be the preferred way to get each result of a list of tasks as soon as they get ready? Meaning that I process the result of a Future as soon as it is completed, not after all tasks are done.

    Thanks for the assistance!

    1 Comment
    2024/05/14
    23:45 UTC

    1

    Closing autocloseables not opened in try with resources

    I have an autoclosable CipherInputStream that I cannot open within a try with resources block due to API design. Not an ideal situation. However, the base InputStream that is used to open the CipherInputStream can be opened in a try with resources block. So, my question is: when the InputStream is autoclosed, does that take care of the CipherInputStream as well, or does that need to be manually closed with a finally block?

    public CipherInputStream getCipherInputStream(final String filename) {
    final CustomEncryptionProvider encryptionProvider = new CustomEncryptionProvider();
    final CipherInputStreamWrapper cipherInputStreamWrapper = null; // contains an autocloseble CipherInputStream, must be fetched from encryption provider
    try (final InputStream inputStream = Files.newInputStream(Paths.get(filename))) {
    cipherInputStreamWrapper = encryptionProvider.getCipherInputStream(inputStream); // inputStream injected into an autocloseble CipherInputStream that is inside cipherInputStreamWrapper
    } catch (IOException e) {
    throw new RuntimeException(e);
    } // do I need a finally block here? or will InputStream closing take care of the CipherInputStream inside cipherInputStreamWrapper?

    return cipherInputStream;
    }

    5 Comments
    2024/05/14
    22:35 UTC

    0

    Will Scala learning as Java Developer be beneficial?

    I am Java developer, wanting to get expertise in Java Springboot development. But project requirement is to learn Scala, should I learn? will it be easy & beneficial? Will it erode Java knowledge from my mind?
    Please Guide ? Thanks in advance.

    7 Comments
    2024/05/14
    20:32 UTC

    2

    Spring - State Machine

    I'm utilizing org.springframework.statemachine:spring-statemachine-core, and I'm uncertain about how to persist the state context. Should I create a separate table for it, or should it be stored in the table that already has a state column?

    2 Comments
    2024/05/14
    20:27 UTC

    2

    How to scheduling method in ExecutorService in call?

    Is there a way, using annotations and any necessary frameworks, to ensure that when an annotated method is called, its execution is scheduled in the priority queue of a thread pool?

    It is important to note that the priority queue depends, among other things, on when the function was added to the queue, i.e. the earlier it is added to the queue, the higher the priority. This also raises the issue of equally annotated function calls, i.e. what is the best approach? Create threads and stop execution until the called annotated method has finished? Create a call stack?

    1 Comment
    2024/05/14
    19:33 UTC

    2

    Unsure how to proceed on a simple code

    I recently started a college course that teaches beginner java. Wow I am hooked now! I have finished all of the assignments due and decided I wanted to experiment and write my own code outside of the class just for fun and growth. So far I have been able to apply what I have learned to make the first aspect of my code successful but I'm getting pretty hung up on the second part.

    I'm writing a program that will ideally calculate the number of fish needed for someone to reach level 99 fishing in RuneScape. So far within the console I've been able to prompt the user to enter their current xp as in integer and the program will then output the xp remaining to reach level 99. After that the console then prompts the user to enter the type of fish.

    This is where I'm stuck. Ideally I want the user to be able to simply type the name of the fish and have the program calculate the number needed (each type of fish has a specific xp value) to reach level 99. My question is: How do I accept user input in the form of a word that will have a numerical value assigned to it?

    runescapeFishing

    6 Comments
    2024/05/14
    16:32 UTC

    1

    Where am I going wrong?

    This is an assignment. im sure my error has to do with executing the draw method in the loop.

    • Create an object of type Rectangle and assign it to shapearray at index/subscript 0
    • Create an object of type Pentagon and assign it to shapearray at index/subscript 1
    • Create an object of type Octagon and assign it to shapearray at index/subscript 2
    • Write a for loop from 0 to 2 and use the objects in shapearray to execute the draw() method
    • Do not declare variables, that has been done for you, use variable i with the loop

    public abstract class Shape {
      protected String type;
      public abstract void draw(); 
    }
    
    public class Circle extends Shape {
      public Circle() { type="Circle"; }
      public void draw() {
        System.out.println("Draw Shape: "
                          + type);
      }
    }
    
    Shape[] shapearray = new Shape[20]; 
    int i;  // variable to use with loop
    
    public class Square extends Shape {
      public Square() { type="Square"; }
      public void draw() {
        System.out.println("Draw Shape: " 
                             + type);
      }
    }
    
    public class Diamond extends Shape {
      public Diamond() { type="Diamond"; }
      public void draw() {
        System.out.println("Draw Shape: " 
                                 + type);
      }
    }
    
    
    
    MY ANSWER:
    
    shapearray[0] = new Rectangle(); 
    shapearray[1] = new Pentagon(); 
    shapearray[2] = new Octagon();
    
    for(i = 0, i < 2, i++) { 
    shapearray[i].draw();        // I believe im wrong here but can figure out the correct way
    }
    
    
    
    
    7 Comments
    2024/05/14
    15:58 UTC

    0

    Trying to build a programm, can you help me understand what should i do ...

    I'm trying to build this program, where the user writes a word and a key number, and as output the program gives the letters moved depending on the key number issued

    for example the user types "a", the key number is 2, and the output will be "C".

    However, if the user types "A" with key number "1" or larger, the program should return from the letter "A", .

    However, I don't know how to build this part of the program, what can I do?

    System.out.println("Please enter a word");
    text = word.next();
    System.out.println("please enter a keynumber:");
    keynumber = input.nextInt();
    char[] encrypt = text.toCharArray();
    for (char c : encrypt) {
    
        c -= keynumber;
        System.out.print(c);}
    7 Comments
    2024/05/14
    11:42 UTC

    2

    Jextract with multiple dlls

    Hi there. This might be a bit of a niche question - if there's a better place to ask please let me know :o)

    I'm using SDL2 with JExtract. I can use the SDL2 functions from Java just fine but not SDL2_Image functions. I generated my wrapper code using JExtract pointing to the SDL_image.h header file 'cos that includes SDL2.h and I want my wrapper to include both parts. When I try to use SDL2_Image functions I get an UnsatisfiedLinkError so I'm pretty sure that I'm geting SDl2.dll loaded but not SDL2_image.dll.

    I'm not sure how to resolve this. I previously tried making SDL2 and SDL2_Image wrapper libraries separately with JExtract but then I ended up getting the SDL2 functions all defined twice.

    In short, I'm not sure how to resolve this.

    Here's how I ran JExtract for my wrapper:

    jextract --include-dir E:\SDL2\include --output src --target-package org.cactuscat.sdl2 --library sdl2 E:\SDL2\include\SDL_image.h
    1 Comment
    2024/05/14
    07:24 UTC

    2

    Java Tracking HTML Hyperlink Use?

    Hi, struggling a little for my theory of computation project. Essentially I'm meant to make a little ~3 page website, track user movement through it, do some random runs, and then have my program spit out a Markov chain probability matrix for the paths taken through the site. What I'm specifically having trouble with is how to literally connect "uses [x] hyperlink in [y] HTML file" to some counter in the Java file.

    I already know how I want to calculate the chain and I don't need help actually programming anything, I just want to know if there's some syntax for this specific thing or a total oversight I'm missing like just doing it in a framework (the professor didn't explicitly suggest or ban using one, his only requirement was "makes a matrix" and "screenshot the console"). Everything I search on the topic either turns results about webscraping, articles that assume I've arbitrarily chosen values for the probability matrix and doesn't feature any means for actually tracking movement, framework ads, or several year old coderanch questions that expand into tracking activity on external sites with all the comments only talking about the ethics of such a task.

    If it helps clear anything up or turn a more concise answer, the project consists of 3 HTML files and 1 Java file. The HTML files are just 3 pages with some plaintext and 2 hyperlinks each. The Java file keeps a hardcoded 1D int array of all possible states (3, referring to each HTML file) and a hardcoded 2D int array (every possible path in 3 "moves", assuming the first position is always the first state- i.e., 4 paths). Each path will have a counter attached to it used in calculating the final probabilities and probably be written to file in some way in order to actually keep track of multiple website visits by reading in a kind of total or consecutive score thus far. As I said, what I'm struggling with is how to have the Java file "see" when a hyperlink is being clicked, and how to differentiate which one it is.

    Thanks in advance.

    2 Comments
    2024/05/14
    07:11 UTC

    1

    Trouble thinking of ideas. Beginner

    Generally a new beginner to Java. I am in a programming course that makes a game and it uses inteliji community edition to programs. I want to program for fun on the side and publish projects, but the thing is, I don't know when to use a certain statement or stuff like that. For example, using for loops to loop through an array list, or when to call a public variable, how to debug, how to make the game successfully work

    1 Comment
    2024/05/14
    02:38 UTC

    2

    This Stupid Little Turtle is Driving Me Crazy

    Hello everyone! Just to clarify, I'm NOT asking for help with homework, I'm asking for help with a concept. I was getting the hang of nested loops but its so frustrating to learn it on my own. I'm trying to create a loop for "tina" the turtle but I'm at a point where I don't know how to fix my code.

    I'm trying to make the turtle go into a triangle loop, it goes forward, left (at an angle), and then another left at an angle.

    Here is what I have so far:

    I know that something it wrong but I can't put my finger on it. I would appreciate any leading question or concept explanations that can help me to fix it on my own. Thank you everyone!

       Turtle tina = new Turtle(0,100);
        tina.penColor("black");
        tina.speed(116);
    
        for(int i=0; i<180; i++); {
          tina.forward(120);
          tina.left(120);
          tina.left(120);
        } 
    9 Comments
    2024/05/13
    22:15 UTC

    1

    Java has anything like Phoenix LiveViews?

    I spent some time with Elixir and Phoenix LiveView is adorable. Not having to deal with Javascript to build the frontend is so good. I'm wondering if anything like this exists for Java.

    2 Comments
    2024/05/13
    21:08 UTC

    Back To Top