2016-07-06 148 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

我的循环工作,并绝对好 –