Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Im trying to print out a string with stored info from a txt file and I can

ID: 3695557 • Letter: J

Question

Java

Im trying to print out a string with stored info from a txt file and I can only get the first digit to be printed out.(Im a beginner)

the txt file looks like this.

2

3

5

7

11

13

17

19

23

My code looks like this

public static void main(String[] args)

   {

       try

       {

       File f = new File("file.txt");

       Scanner input = new Scanner(f);

       String s = "";

       int total = 0;

      

       while(input.hasNextLine())

       {

           s = input.nextLine();

           total = Integer.parseInt("" + s.charAt(0));

           System.out.print(total + " ");

       }

           //System.out.println(total);

       }

       catch(Exception e)

       {

           System.out.println("File not found.");

       }

      

      

   }

}

And the output

2 3 5 7 1 1 1 1 2

Explanation / Answer

You are choosing the first character in this line:

total = Integer.parseInt("" + s.charAt(0));

Modify it to:

total = Integer.parseInt("" + s);

This should work now.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote