javareplit

Why is my project giving me the incorrect output?


I am learning Java, and have a "project" that I need to complete for my class. I've created a "fortune cookie" program, that randomly selects an array index and prints out the corresponding "fortune" from an array of fortunes. For some strange reason, in a sandbox environment my code works, but when I put it on Replit (which is where I have to submit my project from), I'm getting "Hello World!" rather than my fortune. I'm hoping someone can take a look and let me know where it's going wrong (especially considering I don't have "Hello World!" anywhere in my code!).

This is reproduced at , which can also be seen at https://replit.com/@TacticalTaco/FortuneCookie?v=1#Main.java; the code from that project is given below.

import java.util.Random;

class FortuneCookie {
    public static void main(String[] args) {
        Random rand = new Random();
        int upperbound = 13;
        int int_random = rand.nextInt(upperbound);
        String[] fortune_array = {
          "Never try to catch two frogs with one hand.",
          "Flowers leave their fragrance on the hand that bestows them.",
          "If you want your dinner, don’t offend the cook.",
          "Talk doesn’t cook rice.",
          "Not the fastest horse can catch a word spoken in anger.",
          "Spring is sooner recognized by plants than by men.",
          "Never has a man more need of his intelligence than when a fool asks him a question.",
          "A woman that always laughs is everybody’s wife; a man that is always laughing is an idiot.",
          "If you are planning for one year, grow rice. If you are planning for 20 years grow trees. If you are planning for centuries, grow men.",
          "He who asks is a fool for five minutes, but he who does not ask remains a fool forever.",
          "It is better to light a candle than to curse the darkness.",
          "He who opens his heart for ambition, closes it for the rest.",
          "A candle lights others and consumes itself.",
        };
        System.out.println(int_random);
        System.out.println("You're fortune is : \n" + fortune_array[int_random]);
    }
}

My output is

sh -c javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')
 java -classpath .:target/dependency/* Main
Hello world!
 

Solution

  • Most online editors don't allow arbitrary class names. When they compile and run the code, it's going to output a Main.class file with javac, then use java Main (plus some other flags). When you override that, it's going to either throw an error, or output default behavior (depending on the backend system).

    Also, in Java, in general, you're required to have a top-level public class X for any X.java file, even if you have nested class definitions within.