Why do you people have such an unreasonable hatred of putting things into separate functions?
Code:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.InputStream;
public class Rating {
Scanner sc = null;
InputStream source = null;
public Rating(InputStream src) {
source = src;
sc = new Scanner(src);
}
public static String dup(String str, int n) {
StringBuilder ret = new StringBuilder("");
for (int i = 0; i < n; ++i)
ret.append(str);
return ret.toString();
}
public int queryInt(String question) {
int r = 0;
boolean done = false;
while (!done) {
System.out.print(question + " ");
try {
r = sc.nextInt();
done = true;
} catch (InputMismatchException e) {
System.out.println("Sorry, we couldn't parse that.");
sc = new Scanner(source);
}
}
return r;
}
public void showRating(String label, int rating) {
System.out.print(label + " ");
System.out.println(dup("*", rating));
}
public static void main(String[] args) {
Rating op = new Rating(System.in);
int progRating = op.queryInt("How would you rate your computer programming subject?"),
instRating = op.queryInt("And how about your instructor?");
System.out.println("");
op.showRating("Computer programming:", progRating);
op.showRating("Instructor: ", instRating);
}
}
public static void main (String [] args) throws Exception
Don't ever, ever, ever declare something to throw Exception. Doing so renders the whole exception system useless! If at all possible, catch it and deal with it. If not, throw only the exceptions you expect to have to throw.
Importing * from a package is likewise frowned upon, although understandable if you find yourself importing most or all of the classes from the package anyway, which is most certainly not the case here.
Haskell equivalent:
Code:
import System.IO (hSetBuffering, stdin, stdout, BufferMode(NoBuffering))
askQuestion q = do
putStr $ q ++ " "
s <- getLine
case reads s of
(v, "") : _ -> return v
_ -> do putStrLn "Sorry, we couldn't parse that."
askQuestion q
showRating l n = putStrLn $ l ++ ' ' : replicate n '*'
main = do
mapM_ (flip hSetBuffering $ NoBuffering) [stdin, stdout]
p <- askQuestion "How would you rate your computer programming subject?"
i <- askQuestion "And your instructor?"
putStrLn ""
showRating "Computer Programming:" p
showRating "Instructor: " i
Bookmarks