In: Computer Science
Java
How to read a comma separated value file using Scanner
for example Scanner sc = new Scanner(filename);
I need to assign each value separated by a comma to different variable types.
I need a good example to know how it works and implement it in my project
Please only use Scanner to read the file
Sample input.txt

Here, I have 4 different types of data in the following manner
Sample code in java to read this file (code to copy)
import java.util.*;
import java.io.*;
public class Main{
   public static void main(String[] args)throws Exception{
      // open file using Scanner class
      Scanner sc = new Scanner(new File("input.txt"));
      //we tell our scanner that contents are delimited by a comma
      sc.useDelimiter(",");
      // read from scanner until we have contents to read
      while(sc.hasNext()){
         //declare variables to read;
         String name;
         int age;
         double salary;
         char gender;
         String address;
         name = sc.next();
         age=sc.nextInt();
         salary=sc.nextDouble();
         gender=sc.next().charAt(0);
         address=sc.next();
         System.out.println("Name: "+name);
         System.out.println("Age: "+age);
         System.out.println("Salary: "+salary);
         System.out.println("Gender: "+gender);
         System.out.println("Address: "+address+"\n");
      }
   }
}
code screenshot

Code output screenshot
