CS 1110/1111: Introduction to Programming

Lecture 18

Announcements

Test 1 has been graded; see announcement on collab for more.

SEAS students can apply for a CS Minor here; application deadline is March 1st.

Talking Points

csv stands for comma separated value, even though commas are not the only thing used. We'll usually use ";".

The String split method turns a String into a String[]

File inFile = new File("example.csv");
Scanner csvReader = new Scanner(inFile);
while(csvReader.hasNextLine()) {
    String line = csvReader.nextLine();
    String[] parts = line.split(";");
    if (parts.length > 1) { // only use lines with data in them
        for (int i=0; i<parts.length; ++i) {
            System.out.print(parts[i]+" \t");
        }
        System.out.println();
    }
}

You can use this csv file if you wish. Save it in your Eclipse project's directory but outside of the src folder.

You can read from web pages as well as System.in and Files by using the URL class. You have to use the method openStream when you give the URL to the Scanner constructor.

URL page = new URL("http://www.cs.virginia.edu/cs1110/file.csv");
Scanner csvReader = new Scanner(page.openStream());
while(csvReader.hasNextLine()) {
    String line = csvReader.nextLine();
    String[] parts = line.split(";");
    if (parts.length > 1) { // only use lines with data in them
        for (int i=0; i<parts.length; ++i) {
            System.out.print(parts[i]+" \t");
        }
        System.out.println();
    }
}

All websites can be read this way, though usually they look pretty confusing from Java's point of view. This is because they are in HTML, a computer-focused language for describing how a page looks, not in plain text.

CSV reading gives you Strings, but it can be helpful to turn them into numbers.

String s = "123";
String t = "45.67";
int x = Integer.parseInt(s);
double y = Double.parseDouble(t);
Copyright © 2014 by Luther Tychonievich. All rights reserved.