2013-04-15 19 views
0

嗯,我有這個IP列表。修剪文本文件到第一列與java

193.137.150.5    368 ms    DANIEL-PC    
193.137.150.7    95 ms     N/A     
193.137.150.13    37 ms     N/A     
193.137.150.17    33 ms     N/A     
193.137.150.24    238 ms    N/A     
193.137.150.38    74 ms     DUARTE-PC    
193.137.150.41    26 ms     N/A     
193.137.150.52    176 ms    N/A 

我想用java從列表中刪除IP。

這裏是我的代碼:

import java.io.*; 
import java.util.*; 

class trim{ 

    public static void main(String[] args) throws Exception{ 
     String s; 
     char c; 
     int i = 0; 
     Scanner in = new Scanner(System.in); 

     while (in.hasNextLine()){ 
      s = in.nextLine(); 
      c = s.charAt(i); 
      while (c != ' '){ 
       System.out.print(c); 
       i++; 
       c = s.charAt(i); 
      } 
      System.out.println(); 
     } 
    } 
} 

我在做什麼錯?

+1

你什麼輸出後? –

回答

3

在你的循環中,你永遠不會將零點清零i。這意味着你的偏移量在第一行之後的每一行都是錯誤的。

while (in.hasNextLine()){ 
     s = in.nextLine(); 
     c = s.charAt(i); 
     while (c != ' '){ 
      System.out.print(c); 
      i++; 
      c = s.charAt(i); 
     } 
     System.out.println(); 
     i = 0; // Finished with this line 
    } 
+0

非常感謝。我實際上記得那樣做,完全忘了它之間的某個地方。 –

1

你可以簡單地劃分你的字符串一次打印第二部分

while (in.hasNextLine()){ 
    s = in.nextLine(); 
    System.out.println(s.split(" ", 1)[1]); 
} 
0

你不重新初始化我,

while (in.hasNextLine()){ 
     s = in.nextLine(); 
     // reset i so you start reading at line begin 
     i = 0; 
     c = s.charAt(i); 
     while (c != ' '){ 
      System.out.print(c); 
      i++; 
      c = s.charAt(i); 
     } 
     System.out.println(); 
    } 

話雖這麼說,有更簡單的方法,例如使用String.split()

0

您需要重新啓動i = 0。 您可以做到這一點的nextLine呼叫

s = in.nextLine(); 
    i = 0; 
2
while (in.hasNextLine()){ 
    s = in.nextLine(); 
    String[] arr = s.split(" "); // if delimeter is whitespace use s.split("\\s+") 
    System.out.println(arr[0]); 
}