2016-01-21 152 views
0

我的程序大部分運行平穩。只有不正確的部分是變量newsub的最後一個輸入不起作用。程序跳過它並繼續前進。我試圖評論最後一部分,但後來我仍然不被允許輸入任何內容。所以顯然日食是跳過線?我看到了一些帖子,但是當我將第一部分從鍵盤更改爲輸入時,調用了一個錯誤,因爲他們將其視爲新的未調用變量。任何幫助都會很棒! (另外我完全知道我的程序比需要的更長)謝謝!java掃描儀跳過最後輸入

import java.util.Scanner; 

public class ScannerTest1 { 

    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Enter a long string: "); 
     String lin = keyboard.nextLine(); 

     System.out.print("Enter a substring: "); 
     String sub = keyboard.nextLine(); 

     int leng = lin.length(); 
     System.out.println("Length of your string: " + leng); 

     int leng2 = sub.length(); 
     System.out.println("Length of your substring: " + leng2); 

     int mid = lin.indexOf(sub); 

     System.out.println("Starting position of your substring in string: " + lin.indexOf(sub)); 

     System.out.println(lin.substring(0, mid)); 
     System.out.println(lin.substring((mid + leng2 + 1), leng)); 

     System.out.print("Enter a position between 1 and 43: "); 
     int pos = keyboard.nextInt(); 

     System.out.println("The character at position " + pos + " is " + lin.charAt(pos)); 

     System.out.print("Enter a replacement string: "); 
     String newsub = keyboard.nextLine(); 

     System.out.println("Your new string is: " + lin.substring(0, mid) + newsub + lin.substring((mid + leng2 +1), leng)); 

     keyboard.close(); 
    } 

} 

回答

0

這樣做:

System.out.print("Enter a position between 1 and 43: "); 
int pos = keyboard.nextInt(); 
keyboard.nextLine(); 

你需要吃起來是遺留下來的換行字符。如果你不是最後的keyboard.nextLine()將永遠不會允許用戶輸入。

這是nextInt()nextDouble()等的副作用......他們並沒有吃掉新的字符。