2016-05-30 84 views
0

我對這個問題感到困惑,無法理解爲什麼在我輸入第一個數據後程序總是退出。如何輸入字符串數據?爲什麼我的程序在我輸入密鑰後退出

import java.util.Scanner; 
public class Caesar { 

    public static String encode(String enc, int offset) { 
     offset = offset % 26 + 26; 
     StringBuilder encoded = new StringBuilder(); 
     for (char i : enc.toCharArray()) { 
      if (Character.isLetter(i)) { 
       if (Character.isUpperCase(i)) { 
        encoded.append((char) ('A' + (i - 'A' + offset) % 26)); 
       } else { 
        encoded.append((char) ('a' + (i - 'a' + offset) % 26)); 
       } 
      } else { 
       encoded.append(i); 
      } 
     } 
     return encoded.toString(); 
    } 


    public static void main(String[] args) { 

     Scanner in = new Scanner(System.in); 
     System.out.print("Enter key: "); 
     int key = in.nextInt(); 
     System.out.print("Enter line: "); 
     String str = in.nextLine(); 

     System.out.println(Cipher.encode(str, key)); 

    } 
} 
+0

@Jens獲取輸入的readLine - > nextLine –

+0

@ScaryWombat是的,你是對的對不起 – Jens

回答

1

因爲當你進入Key也推<ENTER>關鍵。此CHAR需要在繼續之前被消耗,所以儘量

Scanner in = new Scanner(System.in); 
    System.out.print("Enter key: "); 
    int key = in.nextInt(); 
    in.nextLine(); 
    System.out.print("Enter line: "); 
    String str = in.nextLine(); 

    System.out.println(Cipher.encode(str, key)); 
+0

謝謝你許多! – Andrew

0
Scanner in = new Scanner(System.in); 
     System.out.print("Enter key: "); 
     int key = in.nextInt(); 
     System.out.print("Enter line: "); 
     if (in.hasNext()) { 
      String str = in.nextLine(); 
     } 

,或者你可以在while

相關問題