2016-07-06 135 views
0

爲什麼我的if-else塊沒有檢測到gamma是空的?這是我的代碼。它是一個Spreadsheet應用程序,這是一個保存函數,循環遍歷表中的所有單元格並將其寫入文件。這裏是我的代碼:爲什麼我的工作不正常?

public void Save() { 
     String FileName = JOptionPane.showInputDialog("Please enter the name for your file:"); 

     if (FileName == null) { 
      System.err.println("You didn't enter anything"); 
     } else { 
      int rows = Table.getRowCount(); 
      int columns = Table.getColumnCount(); 
      int alpha = 0; 
      int beta = 1; 
      choicer.setCurrentDirectory(new java.io.File("Desktop")); 
      choicer.setDialogTitle("Save Document"); 
      choicer.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
      choicer.setAcceptAllFileFilterUsed(false); 
      if (choicer.showSaveDialog(new JPanel()) == JFileChooser.APPROVE_OPTION) { 
       dir = String.valueOf(choicer.getSelectedFile()); 
      } 
      File f = new File(dir + "\\" + FileName + ".txt"); 
      try { 
       fos = new FileOutputStream(f); 
       osw = new OutputStreamWriter(fos); 
       w = new BufferedWriter(osw); 
       for (alpha = 0; alpha <= rows - 1; alpha++) { 
        for (beta = 1; beta < columns; beta++) { 
         String gamma = String.valueOf(Table.getValueAt(alpha, beta)); 
         if (gamma != null) { 
          w.write("<%! " + gamma + " !%> "); 
         } else { 
          w.write(" <%! |^-^| !%> "); 
         }       
        } 
        w.write("\n"); 
       } 
      } catch (IOException e) { 
       System.err.println("Some prob dude. Too big for me"); 
      } finally { 
       try { 
        w.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

我試過由重複的東西給出的鏈接,但是這並沒有解決我的問題。如果我做if(gamma != null && !(gamma.isEmpty))那麼只有null寫入文件作爲伽馬值。

+2

也許,伽瑪不是空的......但是空的,不是嗎?檢查如下:「gamma!= null &&!gamma.isEmpty()」 – W0rmH0le

+1

也許你可以減少你的代碼示例到顯着的行,幷包括細節re。 Table.getValueAt()? –

+0

@BrianAgnew我添加了所有的代碼,以防萬一有人想要額外的驗證 –

回答

0

也許,伽馬是空的,但不是null:

變化

if (gamma != null) 

if (gamma != null && !gamma.isEmpty()) 
+0

如果gamma ==「」,它不被認爲是空的嗎? –

+0

Hummm。我需要檢查......最初。我相信一個空格不是空字符串 – W0rmH0le

+1

'isEmpty'的文檔表明它基本上是檢查字符串長度是否等於零的簡寫 - 所以不,由單個空格組成的字符串不被視爲空的,因爲他們有一個非零長度。 – JonK

0

只有三件事情,我能想到的,將導致此。我會在一秒鐘內接觸到這些人。首先,你在用什麼IDE?你有能力設置斷點和觀察變量嗎?這將有助於您解決以下問題。 1.你能確保第一個for循環命中嗎? 2.然後,確保你正在進入第二個循環。 3.最後,字符串gamma的實際值是多少?這是你需要一個斷點的地方,並且當你期待它爲空時檢查這個變量。可能你會看到它不是。當然,假設你的for循環甚至讓你到達那裏。

希望這會有所幫助!

+0

我也同意@Guilherme P。這也可能是原因。 –

+0

我的循環工作,並絕對好 –