2013-01-23 5 views
8

(Aggiornato Domanda)Java: Perché il controllo di " n" non corrisponde Nuove linee utilizzando System.getProperty ("line.separator")

In primo luogo, penso che "\n" è equivalente a System.getProperty("line.separator")

ho scritto alcuni metodi per lavorare con le stringhe alcuni di loro per verificare l'esistenza di una nuova linea di

if (string.charAt(i) == '\n') {//do something;}

ma ho notato che il controllo per "\n" non corrisponde alle nuove linee aggiunte dal System.getProperty("line.separator")

Questo è un SSCCE per dimostrare la mia richiesta !:

Descrizione:
Due stringhe di testo identico; uno alpha_String ha nuove linee aggiunti utilizzando "\n", e gli altri beta_String ha nuove linee aggiunto utilizzando System.getProperty("line.separator")

C'è un metodo denominato String removeExtraNewLines(String) utilizzato per rimuovere eventuali nuove linee extra in una stringa e tornare indietro; come suggerisce il suo header. Le due stringhe filtrate usando questo metodo.

I due pulsanti buttonAlpha e buttonBeta ogni set il testo della JTextArea con la stringa filtrato

Si noterà che il metodo di cattura/partita e rimuovere nuove linee extra di alpha_String ma non fare il stesso con beta_String

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import javax.swing.*; 

public class NewLineTest extends JPanel 
{ 

    JPanel buttonPanel; 
    JPanel textAreaPanel; 
    JButton buttonAlpha; 
    JButton buttonBeta; 
    JTextArea textArea; 
    String n = "\n"; 
    String s = System.getProperty("line.separator"); 
    String alpha_String; 
    String beta_String; 

    public NewLineTest() 
    { 
     createSentencesText(); 
     buttonAlpha = new JButton("Alpha String"); 
     buttonAlpha.addActionListener(eventWatcher); 

     buttonBeta = new JButton("Beta String"); 
     buttonBeta.addActionListener(eventWatcher); 

     textArea = new JTextArea(0, 0); 
     JScrollPane scrollTextArea = new JScrollPane(textArea); 
     scrollTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
     textArea.setEditable(false); 

     buttonPanel = new JPanel(); 
     textAreaPanel = new JPanel(new BorderLayout()); 

     buttonPanel.add(buttonAlpha); 
     buttonPanel.add(buttonBeta); 

     textAreaPanel.add(scrollTextArea, BorderLayout.CENTER); 

     JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textAreaPanel, buttonPanel); 
     splitPane.setDividerLocation(400); 
     splitPane.setResizeWeight(.5d); 
     this.setLayout(new BorderLayout()); 
     this.add(splitPane); 
    } 

    private void createSentencesText() 
    { 
     alpha_String = "A: Let’s go to the beach." + n + n 
       + "B: That’s a great idea." + n 
       + "A: We haven’t been in a while." + n + n 
       + "B: We haven’t been in a month." + n 
       + "A: The last time we went, you almost drowned." + n 
       + "B: No, I didn’t." + n + n + n 
       + "A: Then why did the lifeguard dive into the water?" + n 
       + "B: I think he wanted to cool off." + n 
       + "A: He swam right up to you." + n 
       + "B: And then he turned right around." + n 
       + "A: Maybe you’re right." + n 
       + "B: Maybe we should get going."; 


     beta_String = "A: Let’s go to the beach." + s + s 
       + "B: That’s a great idea." + s 
       + "A: We haven’t been in a while." + s + s 
       + "B: We haven’t been in a month." + s 
       + "A: The last time we went, you almost drowned." + s 
       + "B: No, I didn’t." + s + s + s 
       + "A: Then why did the lifeguard dive into the water?" + s 
       + "B: I think he wanted to cool off." + s 
       + "A: He swam right up to you." + s 
       + "B: And then he turned right around." + s 
       + "A: Maybe you’re right." + s 
       + "B: Maybe we should get going."; 
    } 

    public static String removeExtraNewLines(String s) 
    { 
     String myNewString = s.trim(); 
     StringBuilder stringB = new StringBuilder(); 

     char previouseChar = '~'; 
     for (int i = 0; i < myNewString.length(); i++) 
     { 
      if (i > 1) 
      { 
       previouseChar = myNewString.charAt(i - 1); 
      } 
      if ((myNewString.charAt(i) == '\n') && (previouseChar == '\n')) 
      { 
       continue; 
      } 

      stringB.append(myNewString.charAt(i)); 
     } 
     myNewString = stringB.toString(); 
     return myNewString; 
    } 
    AbstractAction eventWatcher = new AbstractAction() 
    { 
     @Override 
     public void actionPerformed(ActionEvent ae) 
     { 
      Object source = ae.getSource(); 
      if (source == buttonAlpha) 
      { 
       String arranged_string_alpha = removeExtraNewLines(alpha_String); 
       textArea.setText(arranged_string_alpha); 
      } 
      if (source == buttonBeta) 
      { 
       String arranged_string_beta = removeExtraNewLines(beta_String); 
       textArea.setText(arranged_string_beta); 
      } 
     } 
    }; 

    private static void createAndShowGUI() 
    { 
     JFrame frame = new JFrame("NewLine Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(700, 300); 
     frame.add(new NewLineTest(), BorderLayout.CENTER); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       UIManager.put("swing.boldMetal", Boolean.FALSE); 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 

Quindi la domanda: Perché il controllo per "\n" non corrisponde nuove linee con System.getProperty("line.separator")?, E come abbinarli?

+1

Hai verificato che sul tuo sistema, la costante di sistema sia di fatto uguale a ''\ n''? Non dovrebbe richiedere più di un semplice confronto per scoprire, giusto? – BlackVegetable

+1

Prima di tutto, quale sistema operativo stai usando per testarlo? Secondo, 'if (string.charAt (i) == System.getProperty (" line.separator "))' non funziona come previsto? Terzo, hai provato ad usare un debugger per esaminare quale sia il valore di 'System.getProperty (" line.separator ")'? –

+0

Questo articolo potrebbe interessarti http://en.wikipedia.org/wiki/Newline – Pshemo

risposta

20

In primo luogo, penso che "\ n" è equivalente a System.getProperty ("line.separator") tranne che il successivo è indipendente dalla piattaforma.

No, il secondo è specifico della piattaforma. È il modo indipendente dalla piattaforma di ottenere il separatore di riga della piattaforma.

Quindi su Windows, mi aspetto che System.getProperty("line.separator") restituisca "\ r \ n", ad esempio.

Ora come per quello che il tuo textArea utilizza per una nuova riga - che dipende interamente da cosa è textArea - e non ci hai fornito alcuna informazione al riguardo.

+1

Così pignolo con il linguaggio - eppure così corretto. +1 – BlackVegetable

+9

@BlackVegetable: Pedantry è una parte importante dell'essere un ingegnere del software :) –

+0

Ti citerò su questo ora! – BlackVegetable