2013-02-16 79 views
-2

我的程序假設讀取environment.txt,然後重複提示用戶輸入變量名稱,並使用environment.txt中定義的該變量的值作出響應。用戶不斷輸入變量名稱。 (它們可以用CTRL-C終止程序) 在environment.txt中,var1等於Hello var2等於GoodBye var3等於Program,var4等於Music。每次我的程序在輸入輸入時提示用戶輸入時,程序關閉並且不輸出任何內容。有人可以更改我的代碼,我不明白髮生了什麼事情。與我的程序有問題

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.*; 
public class Environment { 

    public static String VariableName() { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter a Variable: "); 
     String userInput = input.nextLine(); 


     if (userInput == "var1") 
     { 
      userInput = "Hello"; 
      return userInput; 
     } 
     else if (userInput == "var2") 
     { 
      userInput = "GoodBye"; 
      return userInput; 
     } 
     else if (userInput == "var3") 
     { 
      userInput = "Program"; 
      return userInput; 
     } 
     else if (userInput == "var4") 
     { 
      userInput = "Music"; 
      return userInput; 
     } 
     else if (userInput == "CTRL-C"); 
     { 
      System.exit(0); 
     } 
      return userInput; 
    } 


    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     File file = new File("environment.txt"); 
     try{ 
      Scanner scanner = new Scanner(file); 
      while (scanner.hasNextLine()) { 
       String line = scanner.nextLine(); 
       System.out.println(line); 

      } 

     } catch (FileNotFoundException e){ 
      System.out.println("File Not Found"); 
     } 
      VariableName(); 
     } 


} 
+0

順利拿到連續輸入,你永遠不打電話給你的方法主要的'體()'。 – madth3 2013-02-16 02:36:23

回答

2

兩件事。

1)查看this article以瞭解在Java中比較字符串的正確方法。

2)您的VariableName()方法中沒有循環,因此您只能走一次,然後退出。

我會打印出用戶輸入,並且對於您失敗的每個測試,打印一個「thisString不等於thatString」。這將幫助您瞭解程序的實際表現。

這應該讓你在那裏。

1

有在源很多問題,

1)以下SRC將導致調用每次System.exit(0);因爲你關閉else if語句可與semi-clolon (;)從而完成else-if條款。

else if (userInput == "CTRL-C"); 

{ 
System.exit(0); 
} 

2)不使用String.equalsString.equalsIgnoreCase方法用於比較。

3)VARIABLENAME方法不循環,從用戶

+1

該分號的好眼睛! – Floris 2013-02-16 12:44:14