java - Checking if String entered is a binary numer, getting incorrect output -
i trying write program check if user-entered string binary number, , if is, output number of 1s in number. had working fine integer value, since int can't hold more 2 billion or whatever max value is, trying rewrite work strings.
as of right now, number enter output "number entered not binary." , when enter 0, stringindexoutofboundsexception. novice programmer, forgive obvious errors may have missed, asking possible solution problem or push in right direction. here code (after trying make work strings rather integers):
import java.util.*; public class binaryhw { public static void main(string[] args) { scanner kb = new scanner(system.in); system.out.println("enter binary number: "); string bin = kb.nextline(); //the method used check whether or not user entered binary //number requires changing value of 'bin'. //therefore, 'origbin' set equal 'bin' later use. string origbin = bin; int count = 0; boolean isbinary = true; /* if bin = 0, loop skipped because * 0 binary number , need not checked. */ while (integer.parseint(bin) != 0) { int lastdigit = bin.charat(bin.length() - 1); if (lastdigit > 1) { system.out.println("number entered not binary."); isbinary = false; break; } else { bin = bin.substring(bin.length() - 2); } } //again, method used count 1s in bin number //requires changing value of origbin, origbin2 introduced string origbin2 = origbin; (int = 0; < origbin.length(); i++) { if (origbin.charat(origbin.length() - 1) == 1) { count ++; origbin2 = origbin.substring(origbin2.length() - 2); } else { origbin2 = origbin.substring(origbin2.length() - 2); } } if (isbinary) if (count == 1) system.out.println("there " + count + " 1 in binary number entered."); else system.out.println("there " + count + " 1s in binary number entered."); } }
i think overcomplicating things... iterate through binary string, , keep track of number of 1's reached. if number other 0 or 1 found, report input non-binary number. below snippet accomplishes this:
public static void main(string[] args) { scanner kb = new scanner(system.in); system.out.println("enter binary number: "); string bin = kb.nextline(); int onecount = 0; boolean validbinarynum = true; (int = 0; < bin.length() && validbinarynum; i++) { char currentchar = bin.charat(i); if (currentchar == '1') onecount++; else if (currentchar != '0') { validbinarynum = false; } } if (validbinarynum && bin.length() != 0) { system.out.println("number of 1's: " + onecount); } else { system.out.println("number not binary"); } }
Comments
Post a Comment