0

I am on an Java encryption program where it prompts user to map his/her own String sequence from A-Z, 0-9, full stop, comma, exclamation mark and Space.

The programs runs like this:

User enter a String of different sequence from this:

String original= "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.,!";
String example= "!,.1234567890QWERTYUIOPASDFGHJKLZXCVBNM"

User will now choose to encrypt his own String.

Example output: 

Text to Encrypt: ENCRYPT
Encrypted Text: 2Q.TSEU

User can also choose to decrypt a String.

Text to Decrypt: 2Q.TSEU
Decrypted Text: ENCRYPT

However, I am unable to take in Space input for user's preferred String to encrypt.

I tried using .nextLine()instead of .next() but I met some bugs.


When I use String textToEncrypt= sc.nextLine(); this is the output I get.

Text to Encrypt: Encrypted Text: 
--------------------------------------------------------------------
(1-Encrypt) (2-Decrypt) (3-Quit): 

Instead of allowing user to enter the text, it jumps to the next line immediately and goes back to the while loop which asks for user's choice.

gymcode
  • 4,431
  • 15
  • 72
  • 128
  • It would really help if you could post a short but *complete* program (with proper indentation) which demonstrates the problem. – Jon Skeet Feb 06 '15 at 11:38
  • possible duplicate of [Reading Strings next() and nextLine() Java](http://stackoverflow.com/questions/8873351/reading-strings-next-and-nextline-java) – user253751 Feb 06 '15 at 11:39

1 Answers1

2

Use nextLine in all places :

while (run) {
  System.out.print("(1-Encrypt) (2-Decrypt) (3-Quit): ");
                option = sc.nextLine().charAt(0); // here
  if (option == '1') {

    System.out.print("\nText to Encrypt: ");
    String userEncrypt = sc.nextLine(); // and here
    ...
Eran
  • 387,369
  • 54
  • 702
  • 768