2017-04-23 30 views
0

代碼是在這裏:如何用逗號在一行顯示文件的輸出?

https://pastebin.com/08KBcnUX

這裏是我的電流輸出:

OUTPUT:

Integer Array Contents: 
, -3, 2, 0, 0, 1, -5 
Total odd numbers: 3 
Odd numbers are: -3 1 -5 0 0 0 
Index of last zero: 3 
Minimum: -5 
Maximum: 2 
Sum: -5 
Element mean is: 0.0 
//1) How do I get rid of the random "," at the beginning? Lol 
//2) How do I get rid of the 0's that are in the "Odd numbers are: " category. 
//3) Mean's not working. What should I do to fix that. Maybe it has something to do  
//with the extra zeroes? I made it into a double and that didnt do anything either. 
+0

您的代碼請 –

+0

在Pastebin中。 – way245

回答

0

您可以使用System.out.print用,而不是像這樣的逗號:

int trues = 0; 
int falses = 0; 
int firstindex = -1;//first index init with -1 to check with it later 
String del = ""; 
int i = 0; 
while (scan.hasNextLine()) { 
    String line = scan.next(); 
    if (line.equals("true")) {//if the line equal true then trues++; 
     if (firstindex == -1) {//if the first index == -1 then assign 
           //it to i number of words 
      firstindex = i; 
     } 
     trues++; 
    } else if (line.equals("false")) {//if the line equal false falses++ 
     falses++; 
    } 
    System.out.print(del + line); 
    del = ","; 
    i++; 
} 
System.out.println(); 
System.out.println("Total TRUEs: " + trues); 
System.out.println("Total TRUEs: " + falses); 
System.out.println("Index of first TRUE: " + 
         (firstindex > -1 ? firstindex : "No true in file")); 

(firstindex > -1 ? firstindex : "No true in file")意味着如果輸入== -1打印沒有真正在文件其他打印索引

輸出

Welcome to the Info-Array Program! 
Please enter the filename for the Boolean values: Boolean Array Contents: 
true,true,false,true,false,true 
Total TRUEs: 4 
Total TRUEs: 2 
Index of first TRUE: 0 
+0

這很好!我將如何去計算TRUE和FALSE總數以及第一個索引的理想輸出? – way245

+0

查看我的編輯@ way245 –

+0

爲什麼這個投票會倒退? –

1

一個更簡單的方法來完成,這將是利用Files#readAllLines讀取File的每一行變成List<Stirng>。然後,您可以使用String#join輕鬆地將每個String與逗號作爲分隔符組合使用。

List<String> lines = Files.readAllLines(file.toPath()); 

String fileContents = String.join(",", lines); 

如果你想返回true元素的總數量,只是StreamList<String>並過濾掉等於true的元素,最後使用Stream#count獲得量:

long numTrueElements = lines.stream().filter(s -> s.equals("true")).count(); 

如果要返回false元素的總數,只需從List<Stirng>行的大小中減去true元素的總數。

int numFalseElements = lines.size() - numTrueElements; 

如果你想第一true元素的索引,那麼你可以使用List#indexOf

int firstTrueIndex = lines.indexOf("true"); 

使用這種方法,你可以溝Scanner和任何環路完全。

+0

這是一個很好的回答,使用java 8,你只需要像這樣改變'int'到'long' long numTrueElements = lines.stream()。filter(s - > s.equals(「true」))。count() ; (+ 1)** –

+1

@YCF_L謝謝你,我已經倒過來了。這是一個很好的例子。 –

+1

@JacobG。如果你不改變它,代碼將不會編譯。加上有**沒有**自動** downcast **。 **擴大**是自動縮小**是明確的。 –

0
String line=null; 
while (scan.hasNextLine()) { 
      line += scan.nextLine()+","; 
     } 
     System.out.println("Boolean Array Contents: "+line); 
int count = line.split(",").length;