Commit 95c82f1b authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch5] Using Scanner to read input from the command line

parent fbd8ea27
Loading
Loading
Loading
Loading
+1 −1
Changes for src/main/java/ch5/Game.java: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -13,7 +13,7 @@ public class Game {
    boolean isAlive = true;

    while (isAlive == true) {
      String guess = helper.getUserInput("enter a number");
      int guess = helper.getUserInput("enter a number");
      String result = theStartup.checkYourself(guess);
      numOfGuesses++;
      if (result.equals("kill")) {
+5 −16
Changes for src/main/java/ch5/GameHelper.java: 5 added lines, 16 removed lines.
Original line number Diff line number Diff line
package ch5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class GameHelper {
  public String getUserInput(String prompt) {
    String inputLine = null;
    System.out.print(prompt + "  ");
    try {
      BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
      inputLine = is.readLine();
      if (inputLine.length() == 0) {
        return null;
      }
    } catch (IOException e) {
      System.out.println("IOException: " + e);
    }
    return inputLine;
  public int getUserInput(String prompt) {
    System.out.print(prompt + ": ");
    Scanner scanner = new Scanner(System.in);
    return scanner.nextInt();
  }
}
 No newline at end of file
+4 −6
Changes for src/main/java/ch5/SimpleStartupTestDrive.java: 4 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -5,7 +5,7 @@ public class SimpleStartupTestDrive {
    SimpleStartup dot = new SimpleStartup();
    int[] locations = {2, 3, 4};
    dot.setLocationCells(locations);
    String userGuess = "2";
    int userGuess = 2;
    String result = dot.checkYourself(userGuess);
    System.out.println(result);
  }
@@ -19,8 +19,7 @@ class SimpleStartup {
    locationCells = locs;
  }

  public String checkYourself(String stringGuess) {
    int guess = Integer.parseInt(stringGuess);
  public String checkYourself(int guess) {
    String result = "miss";
    for (int cell : locationCells) {
      if (guess == cell) {
@@ -28,10 +27,9 @@ class SimpleStartup {
        numOfHits++;
        break;
      }
    } // out of the loop
    } // close for

    if (numOfHits ==
        locationCells.length) {
    if (numOfHits == locationCells.length) {
      result = "kill";
    }
    return result;