Skip to content

Instantly share code, notes, and snippets.

@drpventura
Last active January 22, 2017 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drpventura/b0485e98dbe85c80f533100ba40a46a2 to your computer and use it in GitHub Desktop.
Save drpventura/b0485e98dbe85c80f533100ba40a46a2 to your computer and use it in GitHub Desktop.
Example of using Scanner for I/O from stdin, and files as well as manipulating strings, see video at https://youtu.be/urNqQcqiUTE
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileStringsEx {
public static boolean hasComment(String s) {
return s.indexOf("(*") != -1 && s.indexOf("*)") != -1;
}
public static void main(String[] args) throws FileNotFoundException {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter filename: ");
// String filename = stdin.nextLine();
String filename = "data/sunspots.txt";
Scanner in = new Scanner(new File(filename));
for (int i = 0; i < 10; i++) {
if (!in.hasNextLine()) {
break;
}
// else
String line = in.nextLine();
if (hasComment(line)) {
// do something to remove the comment
int endCommentIndex = line.indexOf("*)");
line = line.substring(endCommentIndex + 2);
}
while (line.charAt(0) == ' ') {
// remove space
}
System.out.println('"' + line + '"');
}
}
}
Copy link

ghost commented Jan 22, 2017

while (line.charAt(0) == ' ') {
                // remove space
}

can be replaced with

line.trim()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment