arrays - Counting numbers in a text file using Java -


this has been troubling me while now. don't tend ask , research, couldn't find answer.

how write program reads text file, , calculate how many times number shows up? i'm huge beginner in java, , programming in general. here's code.

this code generates text file has 100 random numbers

import java.io.*;  public class rolling  {     public static void main (string[] args) throws ioexception     {         int randomnum;          printwriter fileout = new printwriter (new filewriter ("randumnums.txt"));          (int i= 0; < 101; i++)         {             randomnum = (int) (math.random() * 100);              fileout.println (randomnum);         }         fileout.close();     } } 

now trouble i'm having need read file , write code saying x number rolled 3 times. e.g number 4 appeared 5 times in text file, need print "the number 4 rolled 5 times".

import java.io.*;  public class reading  {     public static void main (string[] args) throws ioexception     {         bufferedreader readfile = new bufferedreader (new filereader ("randumnums.txt"));         int number = 0;         int inmarks [] = new int [100];           (int = 0; < 100; i++)         {             inmarks [i] = integer.parseint(readfile.readline());         }        }  } 

you're pretty close. it's clear you're going have keep track of counts in kind of list, , array quite nicely here.

first, after instantiating inmarks, initialize every value in 0:

int inmarks [] = new int [100];   (int = 0; < 100; i++) {     inmarks [i] = 0; } 

then change loop below this:

string nextline = null; while ((nextline = readfile.readline()) != null) {     int thisint = integer.parseint(nextline);     inmarks[thisint] = inmarks[thisint] + 1; } 

inmarks tracks how many times each distinct int rolled in file. i'm going let implement print-out part of assignment, since give better understanding of how solution works.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -