Struggling with java homework...any help?
Go to solution
Solved by Ghost,
Here is some code that does what you want. I left the comments out so you actually have to work out how it works. ![]()
import java.util.Scanner;public class Binary { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); int oneCounter = 0; boolean isBinary = true; for(char c: input.toCharArray()){ switch(c){ case '1': oneCounter++; case '0': break; default: isBinary = false; break; } if(!isBinary)break; } if(isBinary){ System.out.format("The number is binary and has %d 1s\n", oneCounter); } else{ System.out.println("The number is not binary"); } sc.close(); }}

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now