//Scan.java import java.io.Console; public class Scan { private static Console cons = System.console(); public static String getString(String msg){ return cons.readLine(msg); } public static Integer getInteger(String msg){ Integer oi = null; String str = cons.readLine(msg); try{ oi = Integer.valueOf(str); }catch(NumberFormatException e){ System.out.println(e); } return oi; } public static Double getDouble(String msg){ Double od = null; String str = cons.readLine(msg); try{ od = Double.valueOf(str); }catch(NumberFormatException e){ System.out.println(e); } return od; } public static Character getChar(String msg){ Character och = null; String str = cons.readLine(msg); if(str.length() != 0){ och = str.charAt(0); } return och; } public static Boolean getBoolean(String msg){ Boolean yes = null; char ch = ' '; String str = cons.readLine(msg); if(str.length() != 0){ ch = str.charAt(0); } if(ch=='y' || ch=='Y' || ch=='n' || ch=='N'){ yes = ch!='n' && ch!='N'; } return yes; } }
//ScanDriver.java import java.io.Console; public class ScanDriver { public static int floor = 1;//階 public static void main(String[] args) { boolean bool = Scan.getBoolean("階段を上りますか? (y/n): "); System.out.println("echo : " + bool); if(bool){ floor++; System.out.println(floor + "階に上った。"); }else{ System.out.println(floor + "階にいます。"); } } }
ws>javac -encoding UTF-8 ScanDriver.java ws>java ScanDriver 階段を上りますか? (y/n): y echo : true 2階に上った。