Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package numberguessing;
  7.  
  8. import java.util.Scanner;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;
  11.  
  12. /**
  13.  *
  14.  * @author ope
  15.  */
  16.  
  17. // https://pastebin.com/B44h6XjZ
  18. public class NumberGuessing {
  19.  
  20.     /**
  21.      * @param args the command line arguments
  22.      */
  23.     public static void main(String[] args) {
  24.         // TODO code application logic here
  25.        
  26.         int a = 6;
  27.         int b = 0;
  28.         //hhint c = a/b;
  29.         int guess = 0;
  30.         int numberOfGuesses = 0;
  31.         int numberToGuess = (int)( Math.random() * 100 + 1 );
  32.         // Kysytään numeroa, kunnes käyttäjä vastaa oikein
  33.         while( guess != numberToGuess ){
  34.  
  35.             try {
  36.                 guess = userGuess();
  37.             } catch (MyException ex) {
  38.                 System.out.println( "Syötteen tulee olla väliltä 1-100");
  39.                 continue; // Mennään seuraavalle kierrokselle...
  40.             }
  41.             finally {
  42.                 // Suoritetaan joka tapauksessa, tapahtui poikkeus tai ei
  43.             }
  44.  
  45.             if( guess > numberToGuess  ){
  46.                 System.out.println( "Liian suuri");
  47.             }
  48.             else if( guess < numberToGuess ) {
  49.                 System.out.println("Liian pieni");
  50.             }
  51.             numberOfGuesses++;          
  52.         }
  53.         System.out.println( "Oikein! Tarvitsit " + numberOfGuesses + " arvausta.");
  54.     }
  55.    
  56.     public static int userGuess() throws MyException {
  57.         // Luetaan syöte konsolista (Scanner)
  58.         System.out.print("Arvaa luku: ");
  59.         Scanner sc = new Scanner( System.in );
  60.         String input = sc.next();
  61.         int guess = Integer.parseInt( input );
  62.         // Lähetetään oma poikkeus, jos syöte oli jotain muuta kuin 1-100
  63.         if( guess > 100 || guess < 1) {
  64.             throw new MyException(); // Heitetään MyException -poikkeus
  65.         }
  66.         return guess;  
  67.     }
  68. }
  69.  
  70. // Määritellään oma poikkeusluokka "MyException"
  71. class MyException extends Exception {
  72.     public MyException() {
  73.         super("Syöte ei välillä 1-100");
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement