-6

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");
        }   

       }

}
James Mertz
  • 8,459
  • 11
  • 60
  • 87
henry
  • 1
  • 2
  • 2
  • 4
  • 1
    Where do you attempt to count the zeroes...? –  Dec 13 '12 at 06:05
  • 1
    Please mention where is the problem? – AngelsandDemons Dec 13 '12 at 06:06
  • 4
    For one, it's not recommended to drop questions and leave. Since there will be people asking for clarification. Questions tend to get deleted if they are unanswerable - which is the case if the OP disappears and does not stay to answer comments. – Mysticial Dec 13 '12 at 06:06
  • If you aren't going to bother to put in any effort, why should we bother to help you? –  Dec 13 '12 at 07:33

3 Answers3

2

where is your effort? you can simply try (if your string contains only 1s and 0s):

    String[] splitArr = num.split("1");
    String countStr = "";
    for (int i = 0; i < splitArr.length; i++) {
        if( ! splitArr[i].isEmpty() )
            countStr += splitArr[i].length();
    }
    System.out.println(countStr);
vishal_aim
  • 7,636
  • 1
  • 20
  • 23
2

Here you go:

char[] numArray = num.toCharArray();
  int counter=0;
  for(int i=0;i<numArray.length;i++) {
     if(numArray[i]=='0') {
        counter++; 
     }
     if((i==numArray.length-1&&counter>0)||(counter>0&&numArray[i]!='0')) {
        System.out.println("Number of Zeroes: "+counter);
        counter=0;
     }
  }

Some important points:

1) It's best to use an array of char values here, instead of operating using a double, because a char array can store many more values- the example you posted is too long for a double to 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-1 part 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!

username tbd
  • 9,152
  • 1
  • 20
  • 35
  • 1
    So, if line doesn't end with a 0 it will print `Number of Zeroes: 0` at the end. – default locale Dec 13 '12 at 06:18
  • @defaultlocale, almost- if the line ends with more than one non-zero value, it will print `Number of Zeroes: 0` at the end- ending with a single non-zero value would still function fine, which is why I missed the error. You are quite right that my code was flawed though- edited, and thanks for the tip! – username tbd Dec 13 '12 at 06:22
  • You're welcome. By the way, why do you people hate `String.charAt` so much? – default locale Dec 13 '12 at 06:25
  • 1
    @defaultlocale (Not sure if I have to keep tagging you, but oh well), that's a fair question- there's a great evaluation of it here: http://stackoverflow.com/questions/8894258/fastest-way-to-iterate-over-all-the-chars-in-a-string ... in this solution, it was merely a force of habit- using a `char` array is (possibly) as fast as `charAt` for this type of operation. But the array option has more potential later on for other operations, such as swapping values or repeatably checking them, so it's often more useful. – username tbd Dec 13 '12 at 06:35
0
import java.util.*;
import java.io.*;

public class ZeroCounter {

ArrayList <Integer> listOfNumbers = new ArrayList <Integer> ();
DataInputStream inStream;

long inFileSize;
long outFileSize;

// Track how many bytes we've read. Useful for large files.
int byteCount;

    public ZeroCounter() {
    }

//read the file and turn it into an array of integers
public void readFile(String fileName) {

    try {
        // Create a new File object, get size
        File inputFile = new File(fileName);
        inFileSize = inputFile.length();

        // The constructor of DataInputStream requires an InputStream
        inStream = new DataInputStream(new FileInputStream(inputFile));
    }

    // Oops.  Errors.
    catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(0);
    }

    // Read the input file
    try {

        // While there are more bytes available to read...
        while (inStream.available() > 0) {

            // Read in a single byte and store it in a character
            int c = (int)inStream.readByte();

            if ((++byteCount)% 1024 == 0)
                System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");

            // Print the integer to see them for debugging purposes
            //System.out.print(c);
            // Add the integer to an ArrayList
            fileArray.add(c);
        }

        // clean up
        inStream.close();
        System.out.println("File has been converted into an ArrayList of Integers!");
    }

    // Oops.  Errors.
    catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }

    //Print the ArrayList contents for debugging purposes
    //System.out.println(fileArray);
}


public void countZeroes() {
    int zeroCounter = 0;
    for (int i = 0; i < listOfNumbers.size(); i++) {
        if (listOfNumbers.get(i) == 0) {
            zeroCounter++;
        }
        else if (listOfNumbers.get(i) != 0 && zeroCounter > 0) {
            //this only prints the number of zeroes if the zero counter isn't zero
            System.out.println(zeroCounter + " ");
            zeroCounter = 0;
        }

        else {
            //do nothing
        }
    }
}

public static void main(String[] args) {
        ZeroCounter comp = new ZeroCounter();
        comp.readFile("test3.txt");
        comp.countZeroes();
    }
}
hologram
  • 533
  • 2
  • 5
  • 21