Question

In: Computer Science

Java How to read a comma separated value file using Scanner for example Scanner sc =...

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

Solutions

Expert Solution

  • We can use useDelimiter() method of the Scanner class fot this purpose.
  • You should know the datatypes of these values to be read before hand.
  • Lets assume a scenario where there aare multiple lines of input which are spearated by comma in a file named "input.txt"
  • Please take a look at the sample code on how to read these values

Sample input.txt

Here, I have 4 different types of data in the following manner

  • <Name> which is a String
  • <Age> which is an int
  • <Salary> which is a double
  • <Gender> which is a char
  • <Address> which is a line ( String with spaces )

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


Related Solutions

Download the file data.csv (comma separated text file) and read the data into R using the...
Download the file data.csv (comma separated text file) and read the data into R using the function read.csv(). Your data set consists of 100 measurements in Celsius of body temperatures from women and men. Use the function t.test() to answer the following questions. Do not assume that the variances are equal. Denote the mean body temperature of females and males by μFμF and μMμMrespectively. (a) Find the p-value for the test H0:μF=μMH0:μF=μM versus HA:μF≠μM.HA:μF≠μM. Answer (b) Are the body temperatures...
Java Programming: Using textI/O models, create a Write file, Append file, and a Read file. Write...
Java Programming: Using textI/O models, create a Write file, Append file, and a Read file. Write 10 fahrenheit temperature to a text file, append 5 more temperatures, then read these numbers calculating, in a method, the Celsius temperature, and printing the results via another method.
Write a Java program to read in the 10 numbers in the example file Book1.csv provided...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided above. The program should sum all the numbers, find the lowest number, find the highest number, and computer the average. Upon completion of the processing, the program should write a new text file named stats.txt with the information found in the following format where xxx represents a number calculated above. The sum of the numbers is: xxx The lowest number is: xxx The highest...
Using java, I need to make a program that reverses a file. The program will read...
Using java, I need to make a program that reverses a file. The program will read the text file character by character, push the characters into a stack, then pop the characters into a new text file (with each character in revers order) EX: Hello World                       eyB       Bye            becomes    dlroW olleH I have the Stack and the Linked List part of this taken care of, I'm just having trouble connecting the stack and the text file together and...
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
How to read the given structure from a random CSV file separated by commas(which contains no...
How to read the given structure from a random CSV file separated by commas(which contains no headers only the values of the contents of the structure) and then insert in a binary search tree using one of the structure contents as a key i.e. datetime and handle duplicates in binary search tree by implementing link_list.Please develop a C code for this. struct data{ char biker_id[200]; char distance_bike_travelled[200]; char datetime[200]; char count_tripr[200]; }
*Python Stock Exchange Data Problem Expected Duration: 3-6 hours A comma-separated value file stocks_data.csv contains historical...
*Python Stock Exchange Data Problem Expected Duration: 3-6 hours A comma-separated value file stocks_data.csv contains historical data on the Adjusted Closing Price for 3 stocks daily from Jan 2, 2009 to Dec 31,2018. The stocks are Apple (APPL), Microsoft (MSFT) and IBM (IBM). A snippet from the data file looks like the following: Symbol Date Adj. Close MSFT 4/16/2014 35.807358 MSFT 6/21/2010 20.752356 IBM 2/10/2009 68.930023 AAPL 2/14/2018 164.227203 IBM 6/13/2017 141.24379 IBM 12/26/2017 142.835663 MSFT 4/1/2009 15.053272 AAPL 4/17/2009...
How to read a text file and store the elements into a linked list in java?...
How to read a text file and store the elements into a linked list in java? Example of a text file: CS100, Intro to CS, John Smith, 37, 100.00 CS200, Java Programming, Susan Smith, 35, 200.00 CS300, Data Structures, Ahmed Suad, 41, 150.50 CS400, Analysis of Algorithms, Yapsiong Chen, 70, 220.50 and print them out in this format: Course: CS100 Title: Intro to CS Author: Name = John Smith, Age = 37 Price: 100.0. And also to print out the...
C programming language only! a file is given that has comma-separated integers. the files contents are...
C programming language only! a file is given that has comma-separated integers. the files contents are -1,-9,1,45,3,2,1,-1... Create a function that takes as an input a filename and returns an array containing the list of integers in the file
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT