Jar не запускается в командной строке, но в IDE - PullRequest
0 голосов
/ 14 апреля 2020

Я создал программу в IDE, но я не помню, какая это была. Однако я все еще получил код и хотел посмотреть, работает ли он по-прежнему. Поэтому я скомпилировал его, создал .jar-файл и попытался запустить его из командной строки, но он просто переходит на следующую строку и ничего не делает, даже ошибки. Я проверил код и нет ошибок, я знаю это, потому что он работал в IDE. У кого-нибудь есть идеи, как заставить его работать? Вот код:
Main. java

import java.util.Scanner;

public class Main {

public static boolean orun = true;
public static boolean run = false;
public static boolean turn = true;

public static void main(String[] args) {
    long start;
    Shuffle sh = new Shuffle(Read.read());

    // complete game loop if terminated program ends
    while (true) {
        menu();
        // checking if user quit the game
        if (!orun) {
            break;
        }
        start = System.nanoTime();

        Player user = new Player();
        Player comp = new Player();

        // shuffle and hand out the cards
        sh.shuffle();
        sh.split(user, comp);

        // loop for rounds
        while (run) {
            // true: Player
            // false: Computer
            boolean playerWins;
            // Input from computer and player
            try {
                InputMove in = new InputMove(user.getTop(), comp.getTop());
                // detect if it is the turn of the player
                if (turn) {
                    playerWins = in.input();
                    if (!run) {
                        break;
                    }
                } else {
                    System.out.println("\nComputer...");
                    playerWins = in.comp();
                }
                if (playerWins) {
                    turn = true;
                    System.out.println("\nYou won the card!");
                    user.addCard(comp.giveTop());
                    user.addCard(user.giveTop());
                } else {
                    turn = false;
                    System.out.println("\nThe computer won the card!");
                    comp.addCard(user.giveTop());
                    comp.addCard(comp.giveTop());

                }
                // display stats
                System.out.println("\nThe computer has " + comp.getLength() + " cards. ");
                System.out.println("You have " + user.getLength() + " cards. \n");

                // display win message
                if (user.isEmpty()) {
                    System.out.println("The computer won!");
                    run = false;
                    break;
                } else if (comp.isEmpty()) {
                    System.out.println("You won!");
                    run = false;
                    break;
                }
                // IO verification of next round
                in.checknext();
            } catch (IndexOutOfBoundsException e) {
                System.err.println(e);
                run = false;
                break;
            }

        }

        // measure time since start of the game
        long finish = System.nanoTime();
        long timeElapsed = finish - start;
        // convert nanoseconds to seconds
        float timeSeconds = Math.round((timeElapsed / 1000000000.0f) * 10.0f) / 10.0f;
        // display message
        System.out.println("Game ended. ");
        if (timeSeconds > 60) {
            // convert seconds to minutes
            float timeMinutes = Math.round((timeSeconds / 60.0f) * 10.0f) / 10.0f;
            System.out.println("You were " + timeMinutes + " minutes in the game. \n");
        } else {

            System.out.println("You were " + timeSeconds + " seconds in the game. \n");
        }
    }

    System.out.println("Bye, see you next time!");
}

static Scanner sc = new Scanner(System.in);

private static void menu() {
    // create scanner

    // display menu
    System.out.println("1. Start game");
    System.out.println("2. Rules");
    System.out.println("3. Quit game");
    System.out.print("Number between 1 and 3: ");
    // get user input and remove whitespaces
    String rawInput = sc.next();
    rawInput.trim();
    if (rawInput.isEmpty()) {
        System.err.print("please enter a number between 1 and 3! ");
        menu();
    } else {
        // try converting to int and making sure that it is in the right range (1-4)
        try {
            int rawoutput = Integer.parseInt(rawInput);
            if (rawoutput < 4 && rawoutput > 0) {
                switch (rawoutput) {
                case 1:
                    run = true;
                    break;

                case 2:
                    rules();
                    menu();
                    break;

                case 3:
                    orun = false;
                    break;

                default:
                    break;
                }
            } else {
                System.err.println("please enter a number between 1 and 3! ");
                menu();
            }
        } catch (NumberFormatException e) {
            System.err.println("please enter a number between 1 and 3! ");
            menu();
        }
    }
}

private static void rules() {
    System.out.println();
    System.out.println(
            "You and the Computer have seperate decks of cards. If it is your turn, you can pick a value from your top card.");
    System.out.println(
            "The computer tells you its value, in the catergory you have choosen. Then both values are compared with the following concept.");
    System.out.println();
    System.out.println("1. In the categories \"distance\" and \"diameter\" the higher value wins.");
    System.out.println("2. If \"temperature\" is choosen, the more extreme value wins. ( -20°C wins over 15°C )");
    System.out.println("3. The earlier discovery date wins.");
    System.out.println();
    System.out.println("If the values are the same you always win the card.");
    System.out.println(
            "If it is the turn of the computer, it will tell you a value from its card and your value in this category is displayed.");
    System.out.println("The comparing rules also take effect, if it is the computers turn.");
    System.out.println("It is your turn, if you win the round. The same applies for the computer.");
    System.out.println();
    System.out.println("To return to the main menu, type \"exit\" instead of a number");
    System.out.println("or type \"n\", when the game asks if you want to play the next round.");
    System.out.println();
}
}

Shuffle. java:

import java.util.ArrayList;

public class Shuffle {

// all cards
ArrayList<SpaceObject> sol = new ArrayList<SpaceObject>();

// deck of the Computer
ArrayList<SpaceObject> com = new ArrayList<SpaceObject>();
// deck of the Player
ArrayList<SpaceObject> pla = new ArrayList<SpaceObject>();

public Shuffle(ArrayList<SpaceObject> s) {
    sol = s;

}

/**
 * Shuffles the cards
 * 
 * @param sol deck of cards
 * @return shuffled deck of cards
 */

public ArrayList<SpaceObject> shuffle() {
    SpaceObject s;
    double rawrand1;
    double rawrand2;
    int randoutput1;
    int randoutput2;

    for (int i = 0; i < 100; i++) {
        // generate random double between 0 and the end of the list
        int length = sol.size() - 1;
        rawrand1 = Math.random() * length;
        rawrand2 = Math.random() * length;

        // convert to integer
        randoutput1 = (int) rawrand1;
        randoutput2 = (int) rawrand2;

        // swap cards
        s = sol.get(randoutput1);
        sol.set(randoutput1, sol.get(randoutput2));
        sol.set(randoutput2, s);

    }
    return sol;
}

// hand out the cards
public void split(Player user, Player comp) {
    // split in 2 arraylists
    for (int i = 0; i < sol.size(); i++) {
        if (i % 2 == 1) {
            // computer gets the uneven cards
            comp.addCard(sol.get(i));
        } else {
            // player gets the even cards
            user.addCard(sol.get(i));
        }
    }
}
}

Read. java:

import java.io.*;
import java.util.ArrayList;

public class Read {
/**
 * reads card data from file
 * 
 * @return ArrayList of SpaceObjects (cards)
 */
public static ArrayList<SpaceObject> read() {

    String file = "C:\\Data";
    String line;
    String[] iden = new String[2];
    String[] rawval;
    int[] val;
    long dist;

    try {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        ArrayList<SpaceObject> o = new ArrayList<SpaceObject>();
        // read and put raw data in array
        while ((line = br.readLine()) != null) {
            rawval = line.split(", ");
            try {
                val = new int[rawval.length - 2];

                for (int i = 2; i < rawval.length - 1; i++) {
                    val[i - 2] = Integer.parseInt(rawval[i]);
                }

                // identifiers in seperate array
                iden[0] = rawval[0];
                iden[1] = rawval[5];
                /*
                 * distance in long variable
                 * because it can be a very big number
                 */
                dist = Integer.parseInt(rawval[1]);

                // generate Objects
                o.add(new SpaceObject(iden, dist, val));
            } catch (NegativeArraySizeException e) {
            }

        }
        br.close();
        return o;

    } catch (IOException e) {
        System.exit(1);
    }
    return null;

}

}

SpaceObject. java:

public class SpaceObject {
String name;
public long distance;
public int diameter;
public int temperature;
public int discovery;
public String type;

/**
 * A card-object that contains information about an object in space
 * 
 * @param iden name and type of the Object as array in the same order
 * @param dist distance to sun as long
 * @param val  diameter, temperature and discovery date as array in the same
 *             order
 */

// constructor
public SpaceObject(String[] iden, long dist, int[] val) {
    name = iden[0];
    type = iden[1];
    distance = dist;
    diameter = val[0];
    temperature = val[1];
    discovery = val[2];
}

/*
 * Formatting output methods
 * 
 */

/**
 * 
 * @return
 */
public String getDistanceAsString() {
    // checking if distance is in lightyears or not
    if (distance > 525960) {
        /*
         * convert lightminutes to lightyears ( distance / 365,25 / 24 / 60 )
         */
        distance /= 525960;
        return distance + " lightyears";
    }
    return distance + " lightminutes";
}

public String getDiameter() {
    return "The diameter is " + diameter + "km. ";
}

public String getTemperatureAsString() {
    if (temperature > 50) {
        return temperature + "°C hot";
    } else if (temperature > 0) {
        return temperature + "°C warm";
    } else {
        return temperature + "°C cold";
    }
}

public String getDiscovery() {
    if (discovery < 0) {
        return Math.abs(discovery) + " b.C. was its discovery date. ";
    }
    return "It was discovered in " + discovery + ". ";
}

@Override
public String toString() {
    return name;
}

@Override
public boolean equals(Object obj) {
        SpaceObject z =  (SpaceObject)obj;

        if (z.name.equalsIgnoreCase(this.name)) {
            return true;
        }

    return false;
}

}

Player. java:

import java.util.ArrayList;
import java.util.List;

public class Player {

private List<SpaceObject> stack;

public Player() {
    this.stack = new ArrayList<SpaceObject>();
}

public Player(List<SpaceObject> stack) {
    this.stack = stack;
}

public void addCard(SpaceObject card) {
    stack.add(card);
}

/**
 * Removes top level card from stack and returns it
 * 
 * @return
 */
public SpaceObject giveTop() {
    SpaceObject out = stack.get(0);
    stack.remove(stack.get(0));
    return out;
}

public SpaceObject getTop() {
    return stack.get(0);
}

public int getLength() {
    return stack.size();
}

public boolean isEmpty() {
    return stack.isEmpty();

}
}

Сравнить. java:

public class Compare {

public static boolean compare(long mode, long v, long v2) {
    if (v > v2 && mode == 1) {
        Main.turn = true;
        System.out.println("\nYou won the card!");
        return true;
    } else if (v < v2 && mode == 2) {
        Main.turn = true;
        System.out.println("\nYou won the card!");
        return true;
    } else if (v == v2) {
        Main.turn = true;
        System.out.println("\nYou won the card!");
        return true;
    } else {
        Main.turn = false;
        System.out.println("\nThe computer won the card!");
        return false;
    }
}
}

InputMove. java:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class InputMove {
Scanner sc = new Scanner(System.in);
SpaceObject so;
SpaceObject so2;
ArrayList<SpaceObject> sol = Read.read();

/**
 * 
 * @param spob  so2 first card of the computer
 * @param spob2 so first card of the player
 */
public InputMove(SpaceObject spob, SpaceObject spob2) {
    so = spob;
    so2 = spob2;
}

public boolean input() {
    // send information to user
    System.out.println("------------------");
    System.out.println(so.name + ":\n");
    System.out.println("1. Distance to the sun ( " + so.getDistanceAsString() + " )");
    System.out.println("2. Diameter ( " + so.diameter + "km )");
    System.out.println("3. Temperature ( " + so.temperature + "°C )");
    if (so.discovery < 0) {
        System.out.println("4. Discovery date ( " + Math.abs(so.discovery) + "b.C. )");
    } else {
        System.out.println("4. Discovery date ( " + so.discovery + " )");
    }
    System.out.print("Choose a value between 1 and 4... ");
    // get user input and remove whitespaces
    String rawInput = sc.next();
    rawInput.trim();

    // process user input
    if (rawInput.isEmpty()) {
        System.err.println("please enter a number between 1 and 4! ");
        return input();
        // terminates game loop in Main
    } else if (rawInput.equalsIgnoreCase("exit")) {
        Main.run = false;
        return false;
    } else {
        // try converting to int and making sure that it is in the right range (1-4)
        try {
            int rawoutput = Integer.parseInt(rawInput);
            if (rawoutput < 5 && rawoutput > 0) {
                // display the value of the computer
                System.out.println("\nComputer...");
                switch (rawoutput) {
                case 1:
                    System.out.println(so2.name + ":\n");
                    System.out.println("It is " + so2.getDistanceAsString() + " away from the sun.");
                    return so.distance > so2.distance || so.distance == so2.distance;

                case 2:
                    System.out.println(so2.name + ":\n");
                    System.out.println(so2.getDiameter());
                    return so.diameter > so2.diameter || so.diameter == so2.diameter;

                case 3:
                    System.out.println(so2.name + ":\n");
                    System.out.println("It is " + so2.getTemperatureAsString() + ".");
                    return Math.abs(so.temperature) > Math.abs(so2.temperature) || Math.abs(so.temperature) == Math.abs(so2.temperature);

                default:
                    System.out.println(so2.name + ":\n");
                    System.out.println(so2.getDiscovery());
                    return so.discovery < so2.discovery || so.discovery == so2.discovery;
                }
            } else {
                System.err.println("please enter a number between 1 and 4! ");
                return input();
            }

            // if it is not a number
        } catch (NumberFormatException e) {
            System.err.println("please enter a number between 1 and 4! ");
            return input();
            // anything else, that can go wrong, terminates the game
        } catch (Exception e) {
            System.err.println(e);
            Main.run = false;
            Main.orun = false;
            return false;
        }
    }
}

/**
 * generates calculated output from the computer
 * 
 * @return a value of the card of the player, how to compare with the computer,
 *         a value from the card of the computer and index of which value it is
 */
public boolean comp() {
    // sort arraylist and find the index of the card for detecting which value is
    // the best and write mode into variable
    int place = 1;
    for (int i = 0; i < 5; i++) {
        if (sort(place) < sort(i)) {
            place = i;
        }
    }

    // choose output

    switch (place) {
    case 1:
        System.out.println(so2.name + ":\n");
        System.out.println("It is " + so2.getDistanceAsString() + " away from the sun.");
        System.out.println(so.name + ":\n");
        System.out.println("It is " + so.getDistanceAsString() + " away from the sun.");
        return so.distance > so2.distance || so.distance == so2.distance;

    case 2:
        System.out.println(so2.name + ":\n");
        System.out.println(so2.getDiameter());
        System.out.println(so.name + ":\n");
        System.out.println(so.getDiameter());
        return so.diameter > so2.diameter || so.diameter == so2.diameter;

    case 3:
        System.out.println(so2.name + ":\n");
        System.out.println("It is " + so2.getTemperatureAsString() + ".");
        System.out.println(so.name + ":\n");
        System.out.println("It is " + so.getTemperatureAsString() + ".");
        return Math.abs(so.temperature) > Math.abs(so2.temperature) || Math.abs(so.temperature) == Math.abs(so2.temperature);

    default:
        System.out.println(so2.name + ":\n");
        System.out.println(so2.getDiscovery());
        System.out.println(so.name + ":\n");
        System.out.println(so.getDiscovery());
        return so.discovery < so2.discovery || so.discovery == so2.discovery;
    }
}

/**
 * starts next round or exits the game
 */
public void checknext() {
    System.out.print("next round? (Y/N) ");
    String rawInput = sc.next();
    if (rawInput.equalsIgnoreCase("y")) {
        return;
    } else if (rawInput.equalsIgnoreCase("n")) {
        Main.run = false;
        return;
    } else {
        System.err.println("Enter char \"Y\" or \"N\"");
        checknext();
    }
}

/**
 * detects how good a value is on the card
 * 
 * @param mode specifies the value to be sorted by
 * @return index of the card
 */
private int sort(int mode) {
    switch (mode) {
    case 2:
        // add comparator
        Comparator<SpaceObject> c2 = new Comparator<SpaceObject>() {

            @Override
            public int compare(SpaceObject o1, SpaceObject o2) {
                // set criteria
                return o1.diameter - o2.diameter;
            }
        };
        sol.sort(c2);
        break;

    case 3:
        // add comparator
        Comparator<SpaceObject> c3 = new Comparator<SpaceObject>() {

            @Override
            public int compare(SpaceObject o1, SpaceObject o2) {
                // set criteria
                return Math.abs(o1.temperature) - Math.abs(o2.temperature);
            }
        };
        sol.sort(c3);
        break;

    case 4:
        // add comparator
        Comparator<SpaceObject> c4 = new Comparator<SpaceObject>() {

            @Override
            public int compare(SpaceObject o1, SpaceObject o2) {
                // set criteria
                return o2.discovery - o1.discovery;
            }
        };
        sol.sort(c4);
        break;

    default:
        break;

    }

    int indexOf = sol.indexOf(so2);
    return indexOf;
}
}

И, наконец, вот «Данные»:
Солнце, 0, 1392000, 5470, -3500, с
Меркурий, 3, 4879, 170, - 3500, р
Венера, 6, 12104, 460, -3500, р
Земля, 8, 12756, 15, -450, р
Луна, 8, 3474, -77, -3500, м
Марс, 12, 6794, -63, -3500, р
Фобос, 12, 18754, -40, 1877, м
Деймос, 12, 14, -41, 1877, м
Веста, 19, 1060, -126, 1807, а
Церера, 23, 960, -106, 1801, z
Юпитер, 43, 142984, -148, -3500, р
Ио, 43, 3680, -143, 1610, м
Европа, 43, 3122, -149, 1610, м
Ганимед, 43, 5262, -163, 1610, м
Чури, 60, 4, -55, 1969, k
Сатурн, 60, 120400, -178, -3500, р
Титан, 60, 5150, -180, 1655, м
Уран, 120, 51118, -216, 1781, р
Нептун, 240, 49528, -214, 1846, р
Тритон, 240, 2707, -236, 1846, м
Галлей, 300, 15, -45, -240, к
Плутон, 300, 2370, -222, 1930 , z
Charon, 300, 1214, -233, 1978, m
Quaoar, 360, 1070, -215, 2002, a
Makemake, 420, 750, -243, 2005, z
Haumea, 420, 1244, -241, 2004, z
Sedna, 720, 1000, -244, 2003, a
Eris, 840, 2330, -245, 2005, z
Proxima Centauri, 2103840, 196272, 2770, 1915, с
Сириус, 4207680, 2381710, 9627, -3400, с
Wega, 13149000, 3800160, 9330, -3300, с
Арктур, 19460520, 34800000, 4030, -750 , s
Pegasi, 26823960, 1809600, 5400, -3000, s
Alioth, 42602760, 5150400, 9127, -3400, s
Polaris, 226668760, 64032000, 6730, -3400, с
Kepler-452b, 736344000, 20800, -8, 2015, р

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...