Java Program for Valid Binary Number Conversion and Checking | Help Needed

  • Thread starter Thread starter JasonJo
  • Start date Start date
  • Tags Tags
    compsci Homework
Click For Summary
SUMMARY

The discussion focuses on creating a Java program to validate binary number input from users and convert it to decimal. The user initially struggles with checking if the input string contains only '0' and '1'. The suggested solution involves using a for loop to iterate through each character of the string and validate it against the binary criteria. The final code snippet provided demonstrates a correct implementation for checking binary validity using the charAt method.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of string manipulation in Java
  • Basic knowledge of binary number systems
  • Control flow statements in Java (if-else, loops)
NEXT STEPS
  • Learn about Java exception handling for user input validation
  • Explore Java's Integer.parseInt method for binary to decimal conversion
  • Research regular expressions in Java for advanced input validation
  • Study the implementation of user interfaces in Java for better input handling
USEFUL FOR

Java developers, computer science students, and anyone interested in input validation and binary number processing in programming.

JasonJo
Messages
425
Reaction score
2
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 can't seem to properly check to see if its a binary number?

thanks a lot
 
Physics news on Phys.org
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:
Try:

Code:
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
 

Similar threads

  • · Replies 12 ·
Replies
12
Views
2K
Replies
4
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
18K
  • · Replies 2 ·
Replies
2
Views
12K
Replies
5
Views
2K
  • · Replies 16 ·
Replies
16
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 22 ·
Replies
22
Views
6K
  • · Replies 34 ·
2
Replies
34
Views
22K