0

I am attempting to read from a .csv file for my program but we have never read from a .csv file before in my class. I'm not quite sure how to go about it, but this is my attempt so far. I imagine that I am missing some kind of loop that loops through every line of the file but I am not sure how to go about doing that.

Bank bank = new Bank();
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");
Scanner s2 = new Scanner(infile.nextLine());
int accountType = 0;
String accountHolder = "";
double accountInitial = 0.0;
double accountRate = 0.0;
System.out.println("Program 5, Josh Correia, cssc0491");

System.out.println("Creating accounts...");
s2.useDelimiter(",");
if (s2.hasNextInt()) accountType = s2.nextInt();
if (s2.hasNext()) accountHolder = s2.next();
if (s2.hasNextDouble()) accountInitial = s2.nextDouble();
if (s2.hasNextDouble()) accountRate = s2.nextDouble();
    
bank.addNewAccount(new SavingsAccount(accountHolder, accountInitial, accountRate));

This is the file that I am reading from:

1,Waterford Ellingsworth, 4350.0, 0.002
2,Bethanie Treadwell, 500.0, 0.35
3,Ira Standish, 50000, 0.1, 59, 0.1
4,Debi Cardashian, 5100, 0.0
Josh Correia
  • 2,133
  • 1
  • 17
  • 29
  • You don't need two scanners. [Here's an example on how you could do it.](http://stackoverflow.com/questions/14274259/java-read-csv-with-scanner) – EmptyArsenal Mar 20 '17 at 02:31
  • loop over the file, set a string to equal what u read, then split that string by the delimiter (","). Note that string.split() returns an array so set the result equal to that of an array. Enjoy. – SomeStudent Mar 20 '17 at 02:49
  • Why are u not using poi for doing any stuff with csv , if you want i can post an example or you can google it as well. – Monis Majeed Mar 20 '17 at 03:05

2 Answers2

0
File file = new File("C:/Users/Josh/Desktop/prog5input.csv");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
      String str = sc.nextLine();
      String[] arr = str.split(",");
      int accountType = Integer.valueOf(((String)arr[0]).trim());
      ......
}

You can refer to this link about other ways to read file.

Community
  • 1
  • 1
Dave Pateral
  • 1,362
  • 12
  • 20
  • This might be good enough for many uses. But it will break if some of the fields could contain commas (in which case the field would be enclosed in quotes). For general use, it's better to look into a CSV library. – ajb Mar 20 '17 at 03:09
  • yes, good comments. – Dave Pateral Mar 20 '17 at 03:15
0

you could set it to an actual String and then to a ArrayList via the spilt method :

String str = " ";
ArrayList<String> elephantList = Arrays.asList(str.split(","));
no name
  • 72
  • 6