Jump to content

Decimal To Binary

- - - - -

  • Please log in to reply
15 replies to this topic

#1
neshkid123

neshkid123

    Newbie

  • Members
  • PipPip
  • 23 posts
I am new to java and programming and this is my first post. Let me know if I need to do anything or changing anything. Here is my assignment and below everything is what I have done so far. It does not do exactly as I need it to do so any help would be appreciated. my problem right now that I'm stuck on is arr.convert(120); ... I currently have it hard coded and want to make it so it take the input from the user as the argument.

Design and implement a class called DecToBinArray and write a test program called DecToBinArrayTest.

DecToBinArray is utility class that converts a nonnegative decimal number between 0 and 255 into an array of 0's and 1's. For example, you should be able to do the following:
DecToBinArray arr = new DecToBinArray(120);
arr.convert();
System.out.println(arr);

DecToBinArrayTest should also implement toString() method properly so that the above code snippet print out the standard output 01111000.
NOTE: that the length of the array used in DecToBinArray is always 8 since integers from 0 to 255 can be represented with 8 bits.

DecToBinArrayTest reads a string of digits representing a nonnegative integer from 0 to 255. you may read a line of text from the standard in using the following:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
Detailed explanation: NO
Specific requirements:
NOTE: that the length of the array used in DecToBinArray is always 8 since integers from 0 to 255 can be represented with 8 bits.

example: 120 in binary form is 1111000. Array needs to be filled, add 0 in front to make the array full. 01111000

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


public class DecToBinArray{

public static void main(String[] args) {

	

		DecToBinArray arr = new DecToBinArray();

		arr.convert(120);


}


public int[] DecToBinArray(int num){

	int array= num;

	return new int[num];

}

	

public static int[] DecToBinArrayTest(int num){

	Scanner decimal = new Scanner (System.in);

	System.out.println ("Input Decimal number between 0 and 255");

	num = decimal.nextInt();

	System.out.println(num);

	//decimal.close();

	

	while(num < 0 ||  num > 255){

		System.out.println ("Input Decimal number between 0 and 255");

		num = decimal.nextInt();

	}

	return new int[num];

		

}

public static int[] convert(int num){

	int[] array = DecToBinArrayTest(num);

	

	int result=0;

	int base=2;

	int multiplier=1;

	int k = array.length-1;

	while (num > 0)

	{

		

		int residue = num%base;

		num = num/base;

		result = result + residue*multiplier;

		multiplier = multiplier*10; 

	}

	System.out.println ("binary " + result);

	return array;

}

}


Edited by neshkid123, 06 October 2011 - 03:16 PM.


#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Next time post your code within
 tags to make it easier to read. 


For starters, I don't see any constructor in your code. According to the instructions you'll need to be able to do: [quote]DecToBinArray arr = new DecToBinArray(120);[/quote]

The new keyword followed by the class name "DecToBinArray" indicates you'll need a constructor.

Constructor: (Remember constructors have no return type)

[code]

public DecToBinaryArray(int decimalNumber) {

    ...

}


Inside of your constructor is where you'll initialize your variables.
Example:

private int[] array;

private int decimalNumber;

public DecToBinaryArray(int num) { // remember no return type!

    decimalNumber = num; //store your decimal number

    array = new int[8];     // you know your array needs 8 spots

}

...


With this constructor you'll be able to remove your other DecToBinArray methods. All of the work should be done in the "convert" method.
You can also take away the "static" word from your "convert" method and also change it to void.

Why change it to void?
The requirements indicate that you make the call like this:

Quote

arr.convert();

So here, you shouldn't be returning anything. If you WERE returning a value the requirements might look something like:

int[] array = arr.convert()

And if it WERE static, it would look like:

int[] array = DecToBinArray.convert();


The example shows to use a BufferedReader but you're using Scanner in your code.
I'd put the input in the main(...) method.
Using the BufferedReader (Java Platform SE 7 ) class you'll want to use the readLine() method which returns a String.
From here, you'll want to convert this String to an int using Integer's static method parseInt(String theNumber): Integer (Java Platform SE 7 )

Note that the readLine() method allows the user to type in anything including special symbols and letters.
To check for this and kick this data out you can use String's "matches" method: String (Java Platform SE 7 )
You'll have to pass in a certain pattern for this and you can learn more about this if you check here: How to check a String is a numeric type in java - Stack Overflow

Once you've checked your number, and converted it, you can now pass it into the constructor and call your convert() method.

void main(...) { 

    ask_user_to_enter_number

    get_input_using_nextLine()

    check_To_See_If_String_Is_Valid

    convert_s_to_int

    pass_s_to_constructor

    convert();

    print_your_object

}


I also noticed you're missing your toString() method. You'll need to override this method and create the code that prints your binary array in here.

public String toString() {

    //store your binary array here as a string and return that string

}


Half way through this I accidentally pressed the back button on my mouse and lost half of the post!

#3
neshkid123

neshkid123

    Newbie

  • Members
  • PipPip
  • 23 posts
Thanks for the reply will work on this in the morning, If you could....would it be possible if you type up the other half that you said you lost from backspace key?

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You should know about Integer's toString() method, it will be useful I think.
int num = 120;
System.out.println(Integer.toString(num, 2));

Prints: 1111000

#5
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP

neshkid123 said:

Thanks for the reply will work on this in the morning, If you could....would it be possible if you type up the other half that you said you lost from backspace key?

Attempt to solve the problem first and be sure to come back if you need help. Google will be your best friend.

wim DC said:

You should know about Integer's toString() method, it will be useful I think.
int num = 120;

System.out.println(Integer.toString(num, 2));

Prints: 1111000
Thanks wim, I was gonna post this last night but completely forgot.

#6
neshkid123

neshkid123

    Newbie

  • Members
  • PipPip
  • 23 posts
Here is what I have done so far, please show all my mistake and what changes I need to do. I know that these need to fixed, the toString(), convert(), and have no idea for the parseInt().




import java.io.*;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;



public class DecToBinArray1{

	public DecToBinArray1(int num){

		decimalNumber = num;

		array = new int[8];

	}

	public String toString(){

		 array = new DecToBinArray1(decimal);

		return array;

	}

	public void convert(){

	int[] array = dec.toString(reader);	

	int result=0;

	int base=2;

	int multiplier=1;

	int k = array.length-1;

		while (num > 0)

		{

			int residue = num%base;

			num = num/base;

			result = result + residue*multiplier;

			multiplier = multiplier*10; 

		}

	System.out.println ("binary " + result);


	}

		

	private int[] array;

	private int decimalNumber;

}



class DecToBinArrayTest{

	public static void main (String[] args) {

		System.out.println("Enter a decimal to convert to binary ");

		InputStreamReader reader = new InputStreamReader(System.in);

		BufferedReader in = new BufferedReader(reader);

		String dec = in.readLine();

		dec.toString(reader);

		

		DecToBinArray1 DecToConvert = new DecToBinArray1();

		DecToConvert.convert();

		System.out.println(DecToConvert);

		


	public static*int*parseInt(String*dec){

		throws DecToBinArrayTest;

		

	}

	}

}

	


#7
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
String dec = in.readLine();
You have your number stored in a String but you need it as int.
In order to convert your String to an int, you'll need to use the Integer.parseInt(...) method.

Convert string to int : Convert « Language Basics « Java

This line does not match the example you gave in the requirements:
DecToBinArray1 DecToConvert = new DecToBinArray1();
it should be:

DecToBinArray1 DecToConvert = new DecToBinArray1( aInt ); 


I'm not sure what this is:

	public static*int*parseInt(String*dec){

		throws DecToBinArrayTest;

		

	}
But if you added this because of the BufferedReader then you might want to read up on this first: Create BufferedReader from InputStreamReader : BufferedReader « File « Java Tutorial
In short you either throw the exception or surround the BufferedReader section with

try{ 

....

} catch ( Exception e ) { ... }


I don't even think this compiles:
public String toString(){

		 array = new DecToBinArray1(decimal);

		return array;

	}
You're trying to return an array when the method states that you need to return a String.
I'll give you an idea for the toString

public String toString() {

    String s = ""; // s equals nothing right now

    for( loop through array of binary digits ){

            add each individual digit to s

    }

    return s;

}

Also in your convert method, the logic looks wrong but I also never see you setting any individual position of the array.

array[i] = ... ?



#8
neshkid123

neshkid123

    Newbie

  • Members
  • PipPip
  • 23 posts
Tried to do and fix everything getting a bit confused now with all the variable and referencing. Would be great if I can get more details on the parts I need to fix up.



import java.io.*;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;



public class DecToBinArray1{

	public DecToBinArray1(int num){

		decimalNumber = num;

		array = new int[8];

	}

	public String toString(){

		String S= "";

		for(int i = 0; i< 8; i++)

		{

			array[i]= S;

			

		}

		return S;

	}

	public void convert(){

	decimalNumber.toString();	

	

	int result=0;

	int base=2;

	int multiplier=1;

	for(int i=0; i <8; i++)

	{

		do

			array[i] = result;

		

		while (decimalNumber > 0);

		{

			int residue = decimalNumber%base;

			decimalNumber = decimalNumber/base;

			result = result + residue*multiplier;

			multiplier = multiplier*10; 

		}

	}

	System.out.println ("binary " + result);


	}

		

	private int[] array;

	private int decimalNumber;

}



class DecToBinArrayTest{

	public static void main (String[] args) {

		System.out.println("Enter a decimal to convert to binary ");

		InputStreamReader reader = new InputStreamReader(System.in);

		BufferedReader in = new BufferedReader(reader);

		String dec = in.readLine();

		dec.toString(reader);

		

		DecToBinArray1 DecToConvert = new DecToBinArray1();

		DecToConvert.convert();

		

		int i = toString.parseInt(dec);

		System.out.println(i);

		

				

	}


}

	






#9
neshkid123

neshkid123

    Newbie

  • Members
  • PipPip
  • 23 posts
thanks lethalwire , got my program to run correctly now.

Edited by neshkid123, 11 October 2011 - 03:43 PM.


#10
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Perfecto, I was about to check out the code. I've been out of town the last few days so I haven't been around much to reply with anything useful.

#11
neshkid123

neshkid123

    Newbie

  • Members
  • PipPip
  • 23 posts
how can I make a statement that the user input that only accept integers and throws an error message if the user enter something like " )(*&^%$#@! "?

#12
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I use the Scanner class and not BufferedReader + inputStream. It doesn't really matter what you use. I just prefer it due to easier to construct and it doesn't throw exceptions I must catch.


You may have noticed you get a NumberFormatException if you do type in a non-integer number.
You can easily catch the exception and try again if it errored.
        Scanner scanner [COLOR=#339933]=[/COLOR] [COLOR=#000000][B]new[/B][/COLOR] Scanner[COLOR=#009900]([/COLOR][COLOR=#003399]System[/COLOR].[COLOR=#006633]in[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#000066][B]int[/B][/COLOR] number [COLOR=#339933]=[/COLOR] [COLOR=#339933]-[/COLOR][COLOR=#CC66CC]1[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#000066][B]boolean[/B][/COLOR] ok[COLOR=#339933]=[/COLOR] [COLOR=#000066][B]false[/B][/COLOR][COLOR=#339933];

[/COLOR]        [COLOR=#000000][B]while[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#339933]![/COLOR]ok[COLOR=#009900])[/COLOR][COLOR=#009900]{[/COLOR]
            [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]print[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Enter number: "[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#003399]String[/COLOR] dec [COLOR=#339933]=[/COLOR] scanner.[COLOR=#006633]nextLine[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#000000][B]try[/B][/COLOR] [COLOR=#009900]{
[/COLOR]                number [COLOR=#339933]=[/COLOR][COLOR=#003399]Integer[/COLOR].[COLOR=#006633]parseInt[/COLOR][COLOR=#009900]([/COLOR]dec[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]                ok [COLOR=#339933]=[/COLOR] [COLOR=#000066][B]true[/B][/COLOR][COLOR=#339933]; [/COLOR][COLOR=#ff0000]//This line is skipped if parseInt(..) fails.
[/COLOR]            [COLOR=#009900]}[/COLOR] [COLOR=#000000][B]catch[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#003399]NumberFormatException[/COLOR] e[COLOR=#009900])[/COLOR] [COLOR=#009900]{[/COLOR][COLOR=#a9a9a9]/*Do nothing with exception*/[/COLOR] [COLOR=#009900]}
[/COLOR]        [COLOR=#009900]}

[/COLOR]        [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]println[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Correct number: "[/COLOR]  [COLOR=#339933]+[/COLOR] number[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]

This is - however- the quick and dirty way. Making the exception object is expensive. In addition this just looks ugly.


A cleaner way is to test the String before trying to parse it to an int.
This can be done by simply looping over the characters and verifying it's a digit.
When checking a simple character, don't be tempted to write things like this:

[COLOR=#000066][B]char[/B][/COLOR] c [COLOR=#339933]=[/COLOR] [COLOR=#0000FF]'5'[/COLOR][COLOR=#339933];
[/COLOR][COLOR=#000000][B]if[/B][/COLOR][COLOR=#009900]([/COLOR]c[COLOR=#339933]>=[/COLOR][COLOR=#0000FF]'0'[/COLOR] [COLOR=#339933]&&[/COLOR] c[COLOR=#339933]<=[/COLOR][COLOR=#0000FF]'9'[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900]{
[/COLOR]   [COLOR=#666666][I]//isdigit
[/I][/COLOR][COLOR=#009900]}[/COLOR]
The Character class has various methods like "isLetter", "isJavaLetter", "isLowerCase", "isUpperCase",... and obviously "isDigit".
Using the Character's class methods is better since, it should also validate weird signs, like if the program is run in China, and they got some weird symbol for a digit. The if(c>='0' && c<='9') will fail, but Character.isDigit© should pass.

AAaaaanyway, just side-information. On with the String checking:

        Scanner scanner [COLOR=#339933]=[/COLOR] [COLOR=#000000][B]new[/B][/COLOR] Scanner[COLOR=#009900]([/COLOR][COLOR=#003399]System[/COLOR].[COLOR=#006633]in[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#000066][B]boolean[/B][/COLOR] ok[COLOR=#339933];
[/COLOR]        [COLOR=#003399]String[/COLOR] dec[COLOR=#339933];
[/COLOR]  
        [COLOR=#000000][B]do[/B][/COLOR] [COLOR=#009900]{
[/COLOR]            [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]print[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Enter number: "[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            dec [COLOR=#339933]=[/COLOR] scanner.[COLOR=#006633]nextLine[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            ok [COLOR=#339933]=[/COLOR] [COLOR=#000066][B]true[/B][/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#000000][B]for[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#000066][B]char[/B][/COLOR] c [COLOR=#339933]:[/COLOR] dec.[COLOR=#006633]toCharArray[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900])[/COLOR] [COLOR=#009900]{
[/COLOR]                [COLOR=#000000][B]if[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#339933]![/COLOR][COLOR=#003399]Character[/COLOR].[COLOR=#006633]isDigit[/COLOR][COLOR=#009900]([/COLOR]c[COLOR=#009900])[/COLOR][COLOR=#009900])[/COLOR] [COLOR=#009900]{
[/COLOR]                    ok [COLOR=#339933]=[/COLOR] [COLOR=#000066][B]false[/B][/COLOR][COLOR=#339933];
[/COLOR]                [COLOR=#009900]}
[/COLOR]            [COLOR=#009900]}
[/COLOR]       [COLOR=#009900]}[/COLOR] [COLOR=#000000][B]while[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#339933]![/COLOR]ok[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]  
       [COLOR=#000066][B]int[/B][/COLOR] number [COLOR=#339933]=[/COLOR] [COLOR=#003399]Integer[/COLOR].[COLOR=#006633]parseInt[/COLOR][COLOR=#009900]([/COLOR]dec[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]       [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]println[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Correct number: "[/COLOR] [COLOR=#339933]+[/COLOR] number[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]
I don't know how familiar you are with this type of loop yet, if you don't quite get it, it you'll learn it later and here's an equivalent.

        Scanner scanner [COLOR=#339933]=[/COLOR] [COLOR=#000000][B]new[/B][/COLOR] Scanner[COLOR=#009900]([/COLOR][COLOR=#003399]System[/COLOR].[COLOR=#006633]in[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#000066][B]boolean[/B][/COLOR] ok[COLOR=#339933];
[/COLOR]        [COLOR=#003399]String[/COLOR] dec[COLOR=#339933];

[/COLOR]        [COLOR=#000000][B]do[/B][/COLOR] [COLOR=#009900]{
[/COLOR]            [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]print[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Enter number: "[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            dec [COLOR=#339933]=[/COLOR] scanner.[COLOR=#006633]nextLine[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            ok [COLOR=#339933]=[/COLOR] [COLOR=#000066][B]true[/B][/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#000066][B]int[/B][/COLOR] i[COLOR=#339933]=[/COLOR][COLOR=#CC66CC]0[/COLOR][COLOR=#339933];[/COLOR] 
            [COLOR=#000000][B]while[/B][/COLOR][COLOR=#009900]([/COLOR]i[COLOR=#339933]<[/COLOR]dec.[COLOR=#006633]length[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900]{
[/COLOR]                [COLOR=#000066][B]char[/B][/COLOR] c [COLOR=#339933]=[/COLOR] dec.[COLOR=#006633]charAt[/COLOR][COLOR=#009900]([/COLOR]i[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]                [COLOR=#000000][B]if[/B][/COLOR][COLOR=#009900]([/COLOR][COLOR=#339933]![/COLOR][COLOR=#003399]Character[/COLOR].[COLOR=#006633]isDigit[/COLOR][COLOR=#009900]([/COLOR]c[COLOR=#009900])[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900]{
[/COLOR]                    ok [COLOR=#339933]=[/COLOR] [COLOR=#000066][B]false[/B][/COLOR][COLOR=#339933];
[/COLOR]                    [COLOR=#666666][I]//You can 'break' after this, if you know the break command already. Don't bother if you don't.
[/I][/COLOR]                [COLOR=#009900]}[/COLOR] 
                i[COLOR=#339933]=[/COLOR] i [COLOR=#339933]+[/COLOR] [COLOR=#CC66CC]1[/COLOR][COLOR=#339933];[/COLOR] [COLOR=#666666][I]// or i+=1  or  i++;
[/I][/COLOR]            [COLOR=#009900]}
[/COLOR]        [COLOR=#009900]}[/COLOR] [COLOR=#000000][B]while[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#339933]![/COLOR]ok[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#000066][B]int[/B][/COLOR] number [COLOR=#339933]=[/COLOR] [COLOR=#003399]Integer[/COLOR].[COLOR=#006633]parseInt[/COLOR][COLOR=#009900]([/COLOR]dec[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]println[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Correct number: "[/COLOR] [COLOR=#339933]+[/COLOR] number[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]

This is better than the try{}catch(){} simply because it's not there.
But it still looks quite lengthy to me. The next best option is knowing regular expressions.
In regular expressions "\d" stands for 'digit', and "+" stands for '1 or more'. Which means that when a String matches the regular expression "\d+" the String contains only digits. (1 or more digits)

Strings got a 'matches(..)' method, so it's easy. You just have to know regular expressions for it... And escape the backslash with another one as a backslash is 'special' for Java

        Scanner scanner [COLOR=#339933]=[/COLOR] [COLOR=#000000][B]new[/B][/COLOR] Scanner[COLOR=#009900]([/COLOR][COLOR=#003399]System[/COLOR].[COLOR=#006633]in[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#003399]String[/COLOR] num[COLOR=#339933];

[/COLOR]        [COLOR=#000000][B]do[/B][/COLOR] [COLOR=#009900]{
[/COLOR]            [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]print[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Enter number: "[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            num [COLOR=#339933]=[/COLOR] scanner.[COLOR=#006633]nextLine[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]        [COLOR=#009900]}[/COLOR] [COLOR=#000000][B]while[/B][/COLOR] [COLOR=#009900]([/COLOR][COLOR=#339933]![/COLOR]num.[COLOR=#006633]matches[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"[COLOR=#000099][B]\\[/B][/COLOR]d+"[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];

[/COLOR]         [COLOR=#000066][B]int[/B][/COLOR] number [COLOR=#339933]=[/COLOR] [COLOR=#003399]Integer[/COLOR].[COLOR=#006633]parseInt[/COLOR][COLOR=#009900]([/COLOR]num[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]         [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]println[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Correct number: "[/COLOR] [COLOR=#339933]+[/COLOR] number[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]

And finally - This is Scanner specific - the Scanner class has methods to check if what you're going to read is an int or not:
        [FONT=monospace]Scanner scanner [COLOR=#339933]=[/COLOR] [COLOR=#000000][B]new[/B][/COLOR] Scanner[COLOR=#009900]([/COLOR][COLOR=#003399]System[/COLOR].[COLOR=#006633]in[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR][/FONT]
        [COLOR=#000066][B]int[/B][/COLOR] number [COLOR=#339933]=[/COLOR][COLOR=#003399]Integer[/COLOR].[COLOR=#006633]MIN_VALUE[/COLOR][COLOR=#339933];

[/COLOR]        [COLOR=#000000][B]do[/B][/COLOR][COLOR=#009900]{
[/COLOR]            [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]print[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Enter number: "[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#000000][B]if[/B][/COLOR][COLOR=#009900]([/COLOR]scanner.[COLOR=#006633]hasNextInt[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900]{
[/COLOR]                number [COLOR=#339933]=[/COLOR] scanner.[COLOR=#006633]nextInt[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#009900]}[/COLOR] [COLOR=#000000][B]else[/B][/COLOR] [COLOR=#009900]{
[/COLOR]                [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]println[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Fool! You entered <"[/COLOR] [COLOR=#339933]+[/COLOR] scanner.[COLOR=#006633]nextLine[/COLOR][COLOR=#009900]([/COLOR][COLOR=#009900])[/COLOR] [COLOR=#339933]+[/COLOR] [COLOR=#0000FF]">. That ain't no number."[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]            [COLOR=#009900]}
[/COLOR]        [COLOR=#009900]}[/COLOR][COLOR=#000000][B]while[/B][/COLOR][COLOR=#009900]([/COLOR]number [COLOR=#339933]==[/COLOR] [COLOR=#003399]Integer[/COLOR].[COLOR=#006633]MIN_VALUE[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];

[/COLOR]        [COLOR=#003399]System[/COLOR].[COLOR=#006633]out[/COLOR].[COLOR=#006633]println[/COLOR][COLOR=#009900]([/COLOR][COLOR=#0000FF]"Correct number: "[/COLOR] [COLOR=#339933]+[/COLOR] number[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]
The downside is, you still have to get rid of the entered input by doing scanner.nextLine() if the input was no int. (Happens when I say "You fool! ...." )
And also the fact that you loop when number == Integer.MIN_VALUE. It just has to be a number which you don't expect the user to be typing. Integer.MIN_VALUE and MAX_VALUE are always good options for that ^^.
Even tho it's still safer with an extra boolean...

...Yup I felt like typing today :D




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users