I’m trying to write a program that gets a .txt file that only has something like 10000010000010000010001
I’m trying to count the number of zeros and output it like 5 5 5 3. I thought if I convert a string into a double or int I could write an if or for loop.
import java.util.Scanner;
public class test1{
public static void main(String[] args) {
java.io.File test2 = new java.io.File("test3.txt");
try
{
Scanner input = new Scanner(test2);
while(input.hasNext())
{
String num = input.nextLine();
System.out.println(num);
double n = Double.parseDouble(num);
System.out.println(n);
}
}
catch (Exception e){
System.out.println("could not find file");
}
}
}
Here you go:
Some important points:
1) It’s best to use an array of
charvalues here, instead of operating using adouble, because achararray can store many more values- the example you posted is too long for adoubleto handle.2) Most of this should be self-explanatory (at least, if you study it bit-by-bit), but in case the
i==numArray.length-1part is confusing, this ensures that if the string ends with a 0, the final count of 0’s will be printed out as well.This should work for any string you can throw at it- including values besides 0 and 1, if you need support for it!