Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.6 kB
0
Indexable
Never
package sezione15.javaCollections.esercitazione5.pokerChallenge.util;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Console {
	
	private Scanner scan;
	
	public Console() {
		scan = new Scanner(System.in);
	}
	
	public int getInt(String inputMessage, String errorMessage, int from, int to) {
		boolean isLoop = true;
		int result = 0;
		while(isLoop) {
			System.out.println(inputMessage);
			try {
				var input = scan.nextLine();
				input = input.replace(" ", "");
				int number = Integer.parseInt(input);
				if(number >= from && number <= to) {
					result = number;
					isLoop = false;
				} else {
					System.err.println(errorMessage);
				}
			} catch (NumberFormatException | NoSuchElementException e) {
				System.err.println(errorMessage);
			}
		}
		return result;
	}
	
	public int getInt(String inputMessage, String errorMessage) {
		return getInt(inputMessage, errorMessage, Integer.MIN_VALUE, Integer.MAX_VALUE);
	}
	
	public String getString(String inputMessage, String errorMessage) {
		boolean isLoop = true;
		String result = "";
		while(isLoop) {
			System.out.println(inputMessage);
			try {
				result = scan.nextLine();
				isLoop = false;
			} catch (NoSuchElementException e) {
				System.err.println(errorMessage);
			}
		}
		return result;	
	}
	
	public boolean getBoolean(String inputMessage) {
		boolean isLoop = true;
		String input = "";
		boolean result = false;
		while(isLoop) {
			System.out.println(inputMessage);
			try {
				input = scan.nextLine();
				input = input.replace(" ", "").substring(0, 1);
				if(input.equalsIgnoreCase("Y")) {
					result = true;
					isLoop = false;
				} else if(input.equalsIgnoreCase("N")){
					isLoop = false;
				} else {
					System.err.println("Invalid input, enter 'Yes' or 'No'");
				}
			} catch (NoSuchElementException e) {
				System.err.println("Can't be empty, enter 'Yes' or 'No'");
			}
		}
		return result;	
	}
	
	public <T> T getElementFromMenu(List<T> elements, String inputMessage) {
		System.out.println(inputMessage);
		for(int i = 0; i < elements.size(); i++) {
			System.out.println( (i + 1) + ": " + elements.get(i));
		}
		int optionChosen = getInt("Enter the number to choose the specific option: ", "Invalid input, choose one option from the menu", 1,elements.size() );
		return elements.get(optionChosen - 1);
	}
	
	public void printBreak() {
		System.out.println("-".repeat(100));
	}
	
	
	public void close() {
		scan.close();
	}

}