Computer Science 15-100, Fall 2008
Class Notes: Scanner methods and Console UI
Scanner Methods and Console UI
// This programs reads an int value and prints it. // For details, see http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x = scanner.nextInt(); System.out.println(x); } }
Another Example:
// This programs reads two int values and prints their sum. import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x = scanner.nextInt(); int y = scanner.nextInt(); System.out.println(x+y); } }
// This programs reads two double values and prints their sum.
import java.util.Scanner;
class MyCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double x = scanner.nextDouble();
double y = scanner.nextDouble();
System.out.println(x+y);
}
}
// This programs reads two String values and prints their concatenation. import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String x = scanner.next(); // next(), not nextString()! String y = scanner.next(); System.out.println(x+y); } }
// This program reads int values until the sentinel -1,
// and then prints out the sum (not including the sentinel!).
import java.util.Scanner;
class MyCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sentinel = -1;
int sum = 0;
int x = scanner.nextInt();
while (x != sentinel) {
sum += x;
x = scanner.nextInt();
}
System.out.println(sum);
}
}
Or, more concisely (and without duplicate code):
// This program reads int values until the sentinel -1,
// and then prints out the sum (not including the sentinel!).
import java.util.Scanner;
class MyCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sentinel = -1;
int sum = 0;
int x;
while ((x = scanner.nextInt()) != sentinel)
sum += x;
System.out.println(sum);
}
}
// This programs reads two int values and prints their sum. import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int x = scanner.nextInt(); System.out.print("Enter another integer: "); int y = scanner.nextInt(); System.out.println(x+y); } }
// This programs reads two int values and prints their sum. import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("This program reads two values and prints their sum."); System.out.print("Enter an integer: "); int x = scanner.nextInt(); System.out.print("Enter another integer: "); int y = scanner.nextInt(); System.out.println(x + " + " + y + " = " + (x+y)); } }
// This programs reads two int values and prints their quotient. import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("This program reads two values and prints their quotient."); System.out.print("Enter the integer numerator: "); int x = scanner.nextInt(); System.out.print("Enter the integer denominator: "); int y = scanner.nextInt(); if (y == 0) System.out.println("Cannot divide by zero!"); else System.out.println(x + " / " + y + " = " + (x/y)); } }
import java.util.Scanner;
class MyCode {
public static void main(String[] args) {
String s = "Douglas Noel Adams";
Scanner scanner = new Scanner(s);
while (scanner.hasNext())
System.out.println(scanner.next());
}
}
Another example (with a custom delimiter):
import java.util.Scanner;
class MyCode {
public static void main(String[] args) {
String s = "Rome,Paris,Peoria,London,Tokyo";
Scanner scanner = new Scanner(s);
scanner.useDelimiter(",");
while (scanner.hasNext())
System.out.println(scanner.next());
}
}
import java.util.Scanner;
class MyCode {
public static void main(String[] args) {
Scanner scanner = getFileScanner("SampleFile.txt");
while (scanner.hasNext())
System.out.println(scanner.next());
}
// Convenient helper method for reading from a file.
// Returns null if the file is not found (or for any other error).
// You are responsible for using this method, but not
// for writing it (neither on homeworks or tests)!
public static Scanner getFileScanner(String filename) {
Scanner scanner = null;
try { scanner = new Scanner(new java.io.File(filename)); }
catch (Exception e) {
System.out.println("File not found");
return null;
}
return scanner;
}
}
import java.util.Scanner; class MyCode { public static void main(String[] args) { Scanner scanner = getFileScanner("SampleFile.txt"); while (scanner.hasNext()) System.out.println(scanner.nextLine()); } // Convenient helper method for reading from a file. // Returns null if the file is not found (or for any other error). // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static Scanner getFileScanner(String filename) { Scanner scanner = null; try { scanner = new Scanner(new java.io.File(filename)); } catch (Exception e) { System.out.println("File not found"); return null; } return scanner; } }
import java.io.PrintStream; class MyCode { public static void main(String[] args) { PrintStream out = getFilePrintStream("MyOutput.txt"); out.println("This will output to the file 'MyOutput.txt'"); } // Convenient helper method for writing to a file. // Returns null if the file cannot be opened (or for any other error). // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static PrintStream getFilePrintStream(String filename) { PrintStream out = null; try { out = new PrintStream(new java.io.File(filename)); } catch (Exception e) { System.out.println("Error opening file " + filename); return null; } return out; } }
import java.util.Scanner; class MyCode { public static void main(String[] args) { String url = "http://kosbie.net/cmu/fall-08/15-100/handouts/parsely.html"; Scanner scanner = getUrlScanner(url); while (scanner.hasNext()) System.out.println(scanner.nextLine()); } // Convenient helper method for reading from a web page (url). // Returns null if the page cannot be opened (or for any other error). // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static Scanner getUrlScanner(String url) { Scanner scanner = null; try { scanner = new Scanner(new java.net.URL(url).openStream()); } catch (Exception e) { System.out.println("Error opening url " + url); return null; } return scanner; } }
import java.util.Scanner; class MyCode { public static void main(String[] args) { String url = "http://kosbie.net/cmu/fall-08/15-100/handouts/parsely.html"; Scanner scanner = getUrlTextScanner(url); while (scanner.hasNext()) System.out.println(scanner.nextLine()); } // Convenient helper method for reading from a web page (url) as plain text. // Returns null if the page cannot be opened (or for any other error). // On some pages, especially if they contain XML, the spaces may be elided // (sothetextislikethis) -- in that case, try setting the second parameter // to " " or "\n", so spaces or newlines are added after each parsed element. // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static Scanner getUrlTextScanner(String url) { return getUrlTextScanner(url, null); }
public static Scanner getUrlTextScanner(String url, final String dataDelimiter) { Scanner scanner = null; try { final StringBuffer sb = new StringBuffer(); java.io.InputStreamReader reader = new java.io.InputStreamReader( new java.net.URL(url).openStream()); javax.swing.text.html.HTMLEditorKit.ParserCallback parser = new javax.swing.text.html.HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { if (data != null) { sb.append(data); if (dataDelimiter != null) sb.append(dataDelimiter); } } public void handleSimpleTag(javax.swing.text.html.HTML.Tag tag, javax.swing.text.MutableAttributeSet a, int pos) { if (tag.breaksFlow()) sb.append("\n"); } }; new javax.swing.text.html.parser.ParserDelegator().parse(reader, parser, true); scanner = new Scanner(sb.toString()); } catch (Exception e) { System.out.println("Error opening text reader for url: " + url); return null; } return scanner; } }
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem