Last active
January 22, 2017 04:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + '"'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can be replaced with
line.trim()