Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package numberguessing;
- import java.util.Scanner;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author ope
- */
- // https://pastebin.com/B44h6XjZ
- public class NumberGuessing {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- // TODO code application logic here
- int a = 6;
- int b = 0;
- //hhint c = a/b;
- int guess = 0;
- int numberOfGuesses = 0;
- int numberToGuess = (int)( Math.random() * 100 + 1 );
- // Kysytään numeroa, kunnes käyttäjä vastaa oikein
- while( guess != numberToGuess ){
- try {
- guess = userGuess();
- } catch (MyException ex) {
- System.out.println( "Syötteen tulee olla väliltä 1-100");
- continue; // Mennään seuraavalle kierrokselle...
- }
- finally {
- // Suoritetaan joka tapauksessa, tapahtui poikkeus tai ei
- }
- if( guess > numberToGuess ){
- System.out.println( "Liian suuri");
- }
- else if( guess < numberToGuess ) {
- System.out.println("Liian pieni");
- }
- numberOfGuesses++;
- }
- System.out.println( "Oikein! Tarvitsit " + numberOfGuesses + " arvausta.");
- }
- public static int userGuess() throws MyException {
- // Luetaan syöte konsolista (Scanner)
- System.out.print("Arvaa luku: ");
- Scanner sc = new Scanner( System.in );
- String input = sc.next();
- int guess = Integer.parseInt( input );
- // Lähetetään oma poikkeus, jos syöte oli jotain muuta kuin 1-100
- if( guess > 100 || guess < 1) {
- throw new MyException(); // Heitetään MyException -poikkeus
- }
- return guess;
- }
- }
- // Määritellään oma poikkeusluokka "MyException"
- class MyException extends Exception {
- public MyException() {
- super("Syöte ei välillä 1-100");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement