1

I have a txt file with numbers and I must read the file and print stars depending on the numbers that I am given.How can i do that?

public class Testing
{
  public static void main(String [] args)

    throws IOException 
  {

    FileInputStream fileInputStream = new FileInputStream("numbers.txt");
    Scanner scanner = new Scanner(fileInputStream);


    double doubleNum=(scanner.nextDouble());
    int intNumb=(int) doubleNum;
    for (int i=0;i<intNumb;i++)
      while (scanner.hasNextInt())


    {
      System.out.println("*");
    }
  } 
}
ControlAltDel
  • 28,815
  • 6
  • 42
  • 68
Mr George
  • 39
  • 6
  • And what are the numbers you were given to place stars (asterisks) beside? – DevilsHnd Dec 24 '15 at 12:59
  • 1
    Add to your post an example file and the expected outcome, be specific about the problem. – Tamás F Dec 24 '15 at 13:00
  • uhhhh...I see what you're talking about. You are somewhat off base with your code. There are lots of examples in SO for how to use Scanner for reading a file like this one as an example: http://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in-java It will help you get things right. – DevilsHnd Dec 24 '15 at 13:10

2 Answers2

2

Try to be more specific please. What is the input and what is the desired output ? I hope I'll be able to help you if this below doesn't help you.

FileInputStream fileInputStream = new FileInputStream("numbers.txt");
Scanner scanner = new Scanner(fileInputStream);


while (scanner.hasNextDouble()) {
        int num = Double.valueOf(scanner.nextDouble()).intValue();
        for (int i = 0; i < num; i++) {
            System.out.print("*");
        }
        System.out.println();
    }

scanner.close();

In the case you needed outputs to be like **.*** for e.g. 40.001

FileInputStream fileInputStream = new FileInputStream("numbers.txt");
        Scanner scanner = new Scanner(fileInputStream);

        while (scanner.hasNext()) {
            // scanner.next() gets the next token
            // replaceAll() replaces every digits with * (\d is equal to [0-9] and it needs to be escaped with \ giving \\d)
            System.out.println(scanner.next().replaceAll("\\d", "*"));
        }

        scanner.close();
        fileInputStream.close(); 
Cédric M.
  • 1,052
  • 3
  • 12
  • 23
  • Since we're throwing school answers out there then be sure to also apply try/catch so as to handle exceptions. Please try not to do the work for the OP but instead assist them to acquire the solution. :/ – DevilsHnd Dec 24 '15 at 13:27
  • @DevilsHnd he did in his main function. – Cédric M. Dec 24 '15 at 13:28
0

That's the file im given.

The expected output is * depending on each number.

Mr George
  • 39
  • 6