2016-05-30 99 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

相关问题