简体   繁体   中英

Program works and then terminates

I'm trying to do a program for encryption/decryption of strings, and I need to make a menu for the user so he can choose what he'll do with the string he inputs. If the user inputs 1, he can encrypt a string, and if a user selects 2, he can decrypt a string. However -- when he inputs 1, da program just terminates in the consoles, and displayes the terminate Menu java application C:\\Program Files\\Java\\jre7\\bin\\javaw.exe message

Anyone have a clue ?

import java.util.Scanner;

public class Menu {

public static void main(String[] args) {

    String strTarget;

    Scanner in = new Scanner(System.in);

    System.out
            .println("Dobredojdovte vo programata za enkripcija i dekripcija na stringovi --");
    System.out
            .println("Za da enkriptirate string, stisnete 1; Za da dekriptirate string, stisnete 2");
    int choice = in.nextInt();
    if (choice == 1) {
        System.out.println("Vnesete go stringot kojsto sakate da go enkriptirate -- Dozvoleni se samo golemi bukvi i cifri (mali bukvi ne se dozvoleni)");
        strTarget = in.nextLine();
        System.out.println(strTarget);
    }
    if (choice == 2) {
        System.out.println("Vnesete go stringot kojsto sakate da go dekriptirate --");
    }

}

}

Instead of:

strTarget = in.nextLine();

You want:

strTarget = in.next();

I'm not sure the statement that is outputted (not my language), but this returns the next word entered. If you're wanting the entire line, then keep as you were and instead of:

int choice = in.nextInt();

You want:

int choice = in.nextInt();
in.nextLine();

It is worth nothing that in.nextInt() reads a number, not the whole line so in.nextLine() reads the rest of that line. If you want the user to enter a number and you want to ignore the rest of the line you need to call in.nextLine() after it.

Of course it terminates, you're not indicating the program that it must continue asking for input. You need to write your code inside a loop for that!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM