Write a Java test program that accepts a binary number from the user. You should
ID: 3555929 • Letter: W
Question
Write a Java test program that accepts a binary number from the user. You should store the binary number in a String. Your program should then use afor loop to sequence through every character in the String, counting the number of ones, zeros, and other characters. Your code should display the three counters after the loop terminates.
Here is a starter code;
import javax.swing.*;
// count the number of 1s, 0s, and other characters
public class BinaryDigitCounter
{
public static void main(String[] args)
{
String ui; // user input
int zeroCount =0, otherCount = 0;
ui = JOptionPane.showInputDialog(null, "Enter a binary number")
// check each character in the string
// add one to the appropriate counter
for(int i = 0; i < ui.length(); i++)
{
if ( ui.charAt(i) ==`1` )
{
}
} // end for
} // end main
}
Explanation / Answer
import javax.swing.*;
// count the number of 1s, 0s, and other characters
public class BinaryDigitCounter
{
public static void main(String[] args)
{
String ui; // user input
int zeroCount =0, otherCount = 0;
ui = JOptionPane.showInputDialog(null, "Enter a binary number")
// check each character in the string
// add one to the appropriate counter
for(int i = 0; i < ui.length(); i++)
{
if ( ui.charAt(i) ==`1` )
{
oneCount++;
}
else if ( ui.charAt(i) ==`0` ) {
zeroCount++;
}
else otherCount++;
} // end for
} // end main
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.