Execute HQ9+/Java

From Rosetta Code
Revision as of 21:31, 2 August 2009 by rosettacode>Mwn3d (Created page with '{{implementation|HQ9+}}{{collection|RCHQ9+}}Category:JavaThis program accepts input from a file named by its first argument, or std in if no arguments are given. <lang java>i…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Execute HQ9+/Java is an implementation of HQ9+. Other implementations of HQ9+.
Execute HQ9+/Java is part of RCHQ9+. You may find other members of RCHQ9+ at Category:RCHQ9+.

This program accepts input from a file named by its first argument, or std in if no arguments are given.

<lang java>import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.text.MessageFormat; public class HQ9p{

 public static void main(String[] args) throws Exception{
    int acc = 0;
    String code = "";
    BufferedReader input;
    if(args.length > 0){
   	 input = new BufferedReader(new FileReader(args[0]));
    }else{
   	 input = new BufferedReader(new InputStreamReader(System.in));
    }
    while(input.ready()){
   	 code += input.readLine();
    }
    
    for(char instr:code.toCharArray()){
   	 switch(instr){
   	 	case 'q': System.out.println(code);break;
   	 	case 'h': System.out.println("Hello, World!");break;
   	 	case '9': printBottles();break;
   	 	case '+': acc++;break;
   	 	default: //ignore other chars
   	 }
    }
 }
 public static void printBottles(){
    String byob = bottles(99);
    for (int x = 99; x > 0;) {
       System.out.println(byob + " on the wall");
       System.out.println(byob);
       System.out.println("Take one down, pass it around");
       byob = bottles(--x);
       System.out.println(byob + " on the wall\n");
    }
 }
 static String bottles(int n){
    return MessageFormat.format("{0,choice,0#No more bottles|" +
    		"1#One bottle|2#{0} bottles} of beer", n);
 }

}</lang>