Utils.java :  » Game » settlers-of-catan » utils » Java Open Source

Java Open Source » Game » settlers of catan 
settlers of catan » utils » Utils.java
package utils;

import game.Game;
import game.Game.ResourceType;
import gameParts.BoardUtils;

import java.io.*;
import java.net.URL;
import java.util.Scanner;

import log.Logger;
import log.Logger.OutputType;

public class Utils {

  /**
   * Runs another process according to the given command for example - command="java Server.jar"
   * @param command - the command which runs the wanted process
   * @return the created process, of null upon exception
   */
  public static Process runProcess(String command) {
    try {
      return Runtime.getRuntime().exec(command);
    } catch (IOException e) {
      Logger.println(e.getMessage(), OutputType.ERROR);
    }
    return null;
  }

  /**
   * writes a serializable object to file
   * @param path
   * @param o
   * @throws IOException
   * @precondition - o is serializable
   */
  public static void writeObject(String path, Object o) throws IOException {
    File f = new File(path);
    ObjectOutputStream outputStream = 
      new ObjectOutputStream(new FileOutputStream(f.getAbsolutePath()));
    outputStream.writeObject(o);
    outputStream.close();
  }

  /**
   * reads an object from file
   * @param path
   * @return the object read from file
   * @throws Exception
   * @precondition o is serializable and file in path has object of the same type
   * as o written to it.
   */
  public static Object readObject(String path) throws Exception {
    File f = new File(path);
    ObjectInputStream inputStream = 
      new ObjectInputStream(new FileInputStream(f.getAbsolutePath()));    
    Object o = inputStream.readObject();
    inputStream.close();
    return o;
  }

  /**
   * Check if the given array contains the given arg
   * @param array
   * @param arg
   * @return True iff array contains arg
   */
  public static boolean arrayContains(int[] array, int arg) {
    for (int i=0; i<array.length; ++i) {
      if (array[i] == arg) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if the file in the given path exists
   * @param path
   * @return True iff the file in the given path exists
   */
  public static boolean checkIfFileExists(String path) {
    return (new File(path)).exists();
  }

  public static boolean askYesNo(String string) {
    Logger.print(string + "? (y/n): ", OutputType.OUTPUT);
    Scanner in = new Scanner(System.in);
    String readLine = in.nextLine();
    while ((!readLine.contentEquals("y")) && (!readLine.contentEquals("n"))) {
      Logger.println();
      Logger.print("Please enter only y or n. " + string + "? (y/n): ", OutputType.OUTPUT);
      readLine = in.nextLine();
    }
    Logger.println();
    return readLine.contentEquals("y");
  }

  /**
   * @param in - the scanner
   * @return entered valid action menu index, or -1 if an
   * invalid value was entered.
   * 
   * handle receiving action menu index from the input stream.
   * if ? was entered, display the text file.
   */
  public static int getActionFromUser(Scanner in) {
    String input = null;
    int action = -1;
    while (action == -1){
      try{
        input = in.nextLine();
        if (input.charAt(0) == '?'){
          action = -1;
          input = null;
          //Cli.executeDisplayHelp();          
        } else {
          action = Integer.parseInt(input);
        }
      } catch (Exception e) {
        Logger.println("Please enter a number of menu action", OutputType.OUTPUT);
        action = -1;
      }
    }
    return action;
  }
  
  public static ResourceType getResourceTypeFromUser(Scanner in){
    int resourceNum = -1;
    ResourceType resource = ResourceType.NONE;
    try{
      Logger.println("Please enter a number of resource type", OutputType.OUTPUT);
      int i=1;
      for (ResourceType res: ResourceType.values() ){
        String resourceName = Game.getResourceName(res);
        Logger.println(i + ". " + resourceName, OutputType.OUTPUT);
        i++;
      }
      resourceNum = getNumberFromUser("", 1, ResourceType.values().length);
      resource = ResourceType.values()[resourceNum - 1];
      Logger.println("Selected resource: " + Game.getResourceName(resource), OutputType.OUTPUT);
    } catch (Exception e) {
      Logger.println("Failed to get resource type from user.", OutputType.ERROR);
      Logger.println(e.getMessage(), OutputType.ERROR);
    }
    return resource;
  }

  /**
   * @param in - the input stream
   * @return a valid tile character entered by the user,
   * or '0' if no such character was entered.
   * 
   * handle receiving tile character from the input stream.
   * if ? was entered, display the text file.
   */
  public static char getTileCharacterFromUser(Scanner in) {
    String input = null;
    Character tileCharacter = '0';
    while (tileCharacter == '0') {
      try {
        input = in.nextLine();
        tileCharacter = input.charAt(0);
        if (tileCharacter == '?'){
          input = null;
          tileCharacter = '0';
          //Cli.executeDisplayHelp();
        }
      } catch (Exception e) {
        Logger.println("Please enter a character between a and s", OutputType.OUTPUT);
        input = null;
        tileCharacter = '0';
      }
    }
    if ( (Character.toLowerCase(tileCharacter) < 'a') ||
        (Character.toLowerCase(tileCharacter) > 's') ){
      Logger.println("Please enter a character between a and s", OutputType.OUTPUT);
      return '0';
    }
    return tileCharacter;
  }

  /**
   * @param in - the scanner
   * @return entered valid corner index, or -1 if an
   * invalid value was entered.
   * 
   * handle receiving corner number from the input stream.
   * if ? was entered, display the text file.
   */
  public static int getCornerIndexFromUser(Scanner in) {
    String input = null;
    int cornerIndex = -1;
    while (input == null){
      try {
        input = in.nextLine();
        if (input.charAt(0) == '?'){
          cornerIndex = -1;
          input = null;
          //Cli.executeDisplayHelp();
        }
        else {
          cornerIndex = Integer.parseInt(input);
        }
      } catch (Exception e) {
        Logger.println("Please enter a number between 1 and " + 
            BoardUtils.sCornersAmount, OutputType.OUTPUT);
        input = null;
        cornerIndex = -1;
      }
    }
    if ( (cornerIndex < 1) || (cornerIndex > BoardUtils.sCornersAmount) ){
      Logger.println("Please enter a number between 1 and " + 
          BoardUtils.sCornersAmount, OutputType.OUTPUT);
      return -1;
    }
    return cornerIndex;
  }
  
  public static int getNumberFromUser(String msg, int lowerBound, int upperBound) {
    Scanner in = new Scanner(System.in);
    Logger.println(msg, OutputType.OUTPUT);
    boolean badInput = false;
    int userInput = lowerBound - 1;
    while ((userInput < lowerBound) || (userInput > upperBound)) {
      if (badInput) {
        Logger.print("Bad input was given. ", OutputType.OUTPUT);
      }
      badInput = true;
      Logger.println("Please enter a number between " + lowerBound + "-" + upperBound, OutputType.OUTPUT);
      String input = in.nextLine();
      try {
        userInput = Integer.parseInt(input);
      } catch (Exception e) {
        userInput = lowerBound - 1;
      }
    }
    return userInput;
  }
  
  public static String getNonEmptyStringFromUser(){
    Scanner in = new Scanner(System.in);
    boolean gotString = false;
    String s = null;
    while (!gotString){
      if (s!=null){
        Logger.print("Please enter a non-empty string", OutputType.OUTPUT);
      }
      s = in.nextLine();
      gotString = (s.length() > 0);
    }
    return s;
  }
  
  public static URL getURL(String path) {
    return (new Utils()).getUrlByPath(path);
  }

  private URL getUrlByPath(String path) {
    return getClass().getResource(path);
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.