Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Java program to convert and compare integers

  1. #1
    Junior Member luke's Avatar
    Join Date
    May 2009
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Java program to convert and compare integers

    hey everyone i'm trying to create a program where you pick a number between naught and fifteen to match a randomly generated number. here's what i have so far.
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package numberchoice;
    import java.io.*;
    import java.util.*;
     
    /**
     *
     * @author John
     */
    public class Main {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            char Choice = 0;
            // TODO code application logic here
            log("Pick a number between 0 and 15");
            try{
                Choice = (char)System.in.read();
            }catch (IOException ioe){
                System.exit(1);
            }
            Random randomGenerator = new Random();
            int Random = randomGenerator.nextInt(16);
    log("The Number is: "+Random);
    if(Choice == Random){
        log("You have won!");
    }else{
        log("You have lost.");
    }
        }
         private static void log(String aMessage){
        System.out.println(aMessage);
      }
     
     
    }
    and here is the output i get
    run:
    Pick a number between 0 and 15
    0
    The Number is: 0
    You have lost.
    BUILD SUCCESSFUL (total time: 14 seconds)
    could any body help me out with this?
    cheers,
    luke.
    Last edited by Deep_4; November 7th, 2012 at 10:59 PM.


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Thumbs up Re: Converting to and comparing integers.

    Hello luke.

    Welcome to the Java Programming Forums

    There are a few things wrong with your code.

    For a start, you have declared the wrong variable type. If you are working with numbers then you need to use Integer (int). Char is for characters such as A, B, C etc.

    I have rewritten this for you. Please take a look at my example:

    import java.util.Scanner;
     
    public class Luke {
     
        /**
         * JavaProgrammingForums.com
         */
        private static int random, guess;
     
        public static void main(String[] args) {
     
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter a number between 0 - 15");
     
            random = (int)(Math.random() * 15);
            //System.out.println(random);
     
            try{
     
                while(sc.hasNext()){
     
                    guess = sc.nextInt();
     
                    if(guess > 15){
                        System.out.println("Your guess must be less than 15!");
                        System.out.println("Enter a number between 0 - 15");
                    }
                    else if(guess == random){
                        System.out.println("Congratulations! You guessed correctly.");
                        break;
                    }
                    else{
                        System.out.println("Wrong guess. Try again.");
                    }
     
                }
     
            }catch(Exception e){
                System.out.println("You must enter an integer!");
                System.exit(0);
            }
     
        }
     
    }
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  3. The Following User Says Thank You to JavaPF For This Useful Post:

    luke (May 19th, 2009)

  4. #3
    Junior Member luke's Avatar
    Join Date
    May 2009
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Converting to and comparing integers.

    hi mate, thanks for the reply, i'm new to java, and is a subject at school, we havn't been taught about scanners could you please link me to a tutorial so i can learn that aswell?

    thanks for the help!
    cheers,
    luke.

  5. #4
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Converting to and comparing integers.

    Hello luke, no problem.

    Here is the Scanner class API

    Scanner (Java 2 Platform SE 5.0)

    Do you need to complete this without the use of the Scanner class or is my example OK?
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  6. #5
    Junior Member luke's Avatar
    Join Date
    May 2009
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Converting to and comparing integers.

    it does not really matter, it was not a set assignment or anything, we were just creating a number guessing game in class and i couldn't understand why mine would not register, i tried to convert it to integer using
    int newint = (int)Choice
    but it would just print out the ASCII code, but i'm all for learning new methods so it helped a great deal thank you!

  7. #6
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Converting to and comparing integers.

    Hmm this is strange. I compiled the code you submitted above and changed the char variables to int. The problem is, when using System.in.read(); for some reason, if Choice is set to integer, it prints out a different value than from what you input. For example:

    import java.io.*;
    import java.util.*;
     
    /**
     * @author John
     */
    public class Main {
     
        public static void main(String[] args) {
     
            int Choice = 0;
            Random randomGenerator = new Random();
            int Random = randomGenerator.nextInt(16);
            System.out.println(Random);
     
            log("Pick a number between 0 and 15");
     
            try {
                Choice = (int)System.in.read();
                System.out.println(Choice);
            } catch (IOException ioe) {
                System.exit(1);
            }
     
            if (Choice == Random) {
                log("You have won!");
            } else {
                log("The Number is: " + Random);
                log("You have lost.");
            }
        }
     
        private static void log(String aMessage) {
            System.out.println(aMessage);
        }
     
    }
    I have added code to print out the value of Choice once entered. If you enter 5, for some reason it prints out 53?!

    But the problem still remains when we change the Choice variable back to char. It prints out a different value from what you enter.
    This is why Choice never equals Random so we never get a positive result.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  8. #7
    Junior Member luke's Avatar
    Join Date
    May 2009
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Converting to and comparing integers.

    yes this is what i was saying, when you convert the char to and INT it gives you the ASCII value of that char not the char itself.
    Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion
    notice that number 5 has the ascii value of 53....

  9. #8
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Converting to and comparing integers.

    Yes I understand now. I have just done some reading on System.in.read(). I can't remember the last time I used this on it's own.

    Learning Java - Chapter 9 : Java

    We see that System.in is obviously an inelegant and inefficient way to carry out routine text input. We therefore normally wrap this input stream with classes that provide more powerful methods.
    This is why I use the Scanner class...
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  10. #9
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Converting to and comparing integers.

    I was just attempting to fix your original code but I have no idea how to get System.in.read() to output an inputted integer value. I have tried all kinds of conversions but for some reason it's got the better of me! I hope you are happy with my Scanner class solution and continue to use it into the future!
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  11. #10
    Junior Member luke's Avatar
    Join Date
    May 2009
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Converting to and comparing integers.

    haha, thanks mate thought it may have been the case will continue to use the scanner from now!

Similar Threads

  1. How to convert GSM 6.10 wav file to MP3/PCM/OGG/AU format using JAVA?
    By expertise in forum Java ME (Mobile Edition)
    Replies: 4
    Last Post: April 11th, 2014, 03:13 AM
  2. Replies: 5
    Last Post: May 21st, 2009, 03:45 AM
  3. Replies: 4
    Last Post: May 1st, 2009, 04:32 PM
  4. Program to convert Hexadecimal to its Character equivalent
    By nathanernest in forum Java Theory & Questions
    Replies: 2
    Last Post: April 8th, 2009, 04:12 AM
  5. Comparing hash functions and collision resolutions
    By dansongarcia in forum Collections and Generics
    Replies: 0
    Last Post: November 11th, 2008, 10:50 AM