Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: More CompSci homework help needed

  1. Jun 24, 2005 #1
    hey I need to write a Java program to ask the user for a string input, that should be a binary number. i am to check if the string input is a valid binary number and then convert it into decimal. i know how to program the converting into decimal, but i am having a nightmare as to checking whether or not it is a binary number.

    i used the following if condition in my program (psuedo code is used to simpifly it)

    num1 = the string to be input by the user
    i = 0;
    z = length of the string
    while (i < z)
    if (character i of the string is not equal to 0 and it is not equal to 1) //character i would be the 0th character, using 0 indexing
    print the number input is not a valid binary number
    else
    i = i + 1 //search the entire string

    anyone see why i cant seem to properly check to see if its a binary number?

    thanks a lot
     
  2. jcsd
  3. Jun 24, 2005 #2
    check brackets and if your if condition is indeed the one you put there.

    OR you can revers the if and else.

    plus you don't have a termination condition. to exit while loop
     
    Last edited: Jun 24, 2005
  4. Jun 26, 2005 #3
    Try:

    Code (Text):

    String input = <input from user>...

    for (int i = 0; i < input.length(); i++) {
        if ((input.charAt(i) != '0') && (input.charAt(i) != '1')) {
            // error and quit...
        }
    }

    // success
     
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook