Check if the input number is in a valid binary format - java

i tried to make a simple program,which check if the input number from the user is a binary number and that number is in correct binary format -> without leading zeros. That below is my code,but it doesn't work. I would appreciate if someone could help.
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
num = sl.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
if (firstDigit>0||firstDigit==1 ){
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
} else System.out.printf("WARNING: The number starts with 0");
}
}

There are a better solution, you can check if your input contain only 0 and 1 and the input great then 0 then valide number, so instead you can use String for example :
String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
System.out.println("Correct number :" + num);
}else{
System.out.println("Not Correct number!");
}
num.matches("[01]+") will check if your input contain only 0 and 1.
!num.startsWith("0") this to answer this part without leading zeros
Test:
10010 -> Correct number :10010
00001 -> Not Correct number!
11101 -> Correct number :01101
98888 -> Not Correct number!

You can try something like this:
public static void main(String args[]) {
boolean binary=true; // boolean for final decision
String input;
int counter=0; // to count how many leading zeros there are in the input
int target = 5; // specify how many leading zeros allowed!!
Scanner in = new Scanner(System.in);
input = in.nextLine(); // take the entire line as a String
//first loop through the whole input to check for any illegal entry (i.e. non digits)
for(char digit : input.toCharArray()){
if(!Character.isDigit(digit)){ // catch any non-digit !
System.out.println("Illegal Input Found!"); // inform user and exit
System.exit(0);
}
if(digit!='0' && digit!='1'){ // check if it's not 1 and not 0
binary = false;
}
}
// now if there are no illegal inputs, check if it starts with leading zeros
if(input.charAt(0)=='0'){ // potential leading zeros, check the rest
while(input.charAt(counter)=='0'){ // while there are followed zeros
counter++;
if(counter>target && binary){ // leading zeros only in case it's a binary
System.out.println("Illegal Leading Zeros!");
System.exit(0);
}
}
}
// now if your program reach this point that means the input is valid and doesn't contain leading zeros in case it's a binary
if(binary){
System.out.println("It is a binary number");
}
else{
System.out.println("It is NOT a binary number");
}
}
Test:
01010101 -> It is a binary number
01010105 -> It is NOT a binary number
0000001 -> Illegal Leading Zeros!
0000005 -> It is NOT a binary number
000000A -> Illegal Input Found!

Why not simply use the standard library methods?
static boolean isValidBinary(final int input) {
final String binary = String.valueOf(input);
return binary.replaceAll("[01]", "").isEmpty() && !binary.startsWith("0");
}

you should not use sl.nextInt(); it will transfer '011' to 11, so when user input '011', the variable 'num' get the int value 11.
You should simply use sl.next() to get the input of user.

I think you need to check your "if" condition before the while, because you don't want that the number starts with 0, right? so... just ask for it, I have tryied and worded fine to me:
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
String input = sl.next();
num = Integer.parseInt(input);
String firstDigit = (input.length() > 0 ? input.substring(0, 1) : "" );
if (firstDigit.equals("0")) {
System.out.printf("WARNING: The number starts with 0");
} else {
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
}
}
}
The rest of your code Fulfills its mission! It tells you if the number is binary or not, and now plus tells you if your code begins with useless zeros

import java.util.*;
public class BinaryTest {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
int count=0;
boolean check=true;
System.out.print("Enter a number: ");
int num=input.nextInt();
for(int i=0; i<=num; i++){
count=num%10;
if(count>1) {
check=false;
break;
}
else {
check=true;
}
num=num/10;
}
if(check)
System.out.println("Binary");
else
System.out.println("Not Binary");
}
}

Related

Exception in thread "main" java.lang.NumberFormatException: For input string: "/3"

Below are the code. To fix the error, I simply rewrote the code in getFraction() method to den = Integer.parseInt(fracValue.substring(fracValue.indexOf("/")+1, fracValue.length())) , by adding +1. I have never seen or learn this during my courses and I just encounter this while doing project. I want to understand what the code did in num = Integer.parseInt(fracValue.substring(0, fracValue.indexOf("/"))) and den = Integer.parseInt(fracValue.substring(fracValue.indexOf("/"), fracValue.length())), we are converting the numerator to int and the num is all the values before the / and the den is all the values after the /. Am I right ? My second question is that why do we need to add +1 after the indexOf("/") ? Is it so we are taking the values after the /?
import java.util.Scanner;
public class FractionCalculator {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
intro();
while (true) {
String operation = getOperation();
Fraction frac1 = getFraction();
Fraction frac2 = getFraction();
Fraction result = new Fraction(1,1);
String result2 = "";
if (operation.equals("=")) {
System.out.println(frac1+" "+operation+" "+frac2+" is "+frac1.equals(frac2));
} else {
if (operation.equals("+")) {
result=frac1.add(frac2);
} else if (operation.equals("-")) {
result=frac1.subtract(frac2);
} else if (operation.equals("/")) {
if(frac2.getNumerator()==0) {
result2="Undefined";
} else {
result=frac1.divide(frac2);
}
} else if (operation.equals("*")) {
if(frac2.getNumerator()==0) {
result2 = "Undefined";
} else {
result=frac1.multiply(frac2);
}
}
//print results
} if (result2!="") {// division and multiplication by zero is undefined
System.out.println(frac1+" "+operation+" "+"0"+" = "+result2);
} else if (result.getNumerator()%result.getDenominator() == 0) {
System.out.println(frac1+" "+operation+" "+frac2+" = "+(result.getNumerator()/ result.getDenominator()));
} else {
System.out.println(frac1+" "+operation+" "+frac2+" = "+result.toString());
}
}
}
public static void intro() {
System.out.println("\nThis program is a fraction calculator");
System.out.println("It will add, subtract, multiply and divide fractions until you type Q to quit.");
System.out.println("Please enter your fraction in the form a/b, where a and b are integers.");
for (int i=0; i<80; i++) {
System.out.print("-");
}
}
public static String getOperation() {
System.out.println("\nPlease enter an operation (+, -, /, *, = or \"Q\" to quit): ");
Scanner input = new Scanner(System.in);
String operation = input.nextLine();
int x = 0;
while (x == 0) {
if (operation.equals("+") || operation.equals("-") || operation.equals("/") || operation.equals("*") || operation.equals("=")) {
x++;
} else if (operation.equalsIgnoreCase("q")) {
System.exit(0);
} else {
System.out.println("Invalid input, enter valid operation (+, -, /, *, = or \"Q\" to quit)");
operation = input.nextLine();
}
}
return operation;
}
public static boolean validFraction(String input) {
boolean valid;
if (input.startsWith("-")) {
input = input.replaceFirst("-",""); // or use 'input.substring("1", input.length())';
}
if (input.contains("-") || input.charAt(input.indexOf("/")+1)==('0') || input.contains(" ")) {
valid = false;
} else if (input.contains("/")) {
input = input.replace("/", "");
}
if (input.matches("^[0-9]+$") && input.length() > 0) {
valid = true;
} else {
valid = false;
}
return valid;
}
public static Fraction getFraction() {
System.out.println("Please enter a fraction (a/b) or integer (a): ");
String fracValue = input.nextLine();
//validate input
while (!validFraction(fracValue)) {
System.out.println("Please enter a fraction (a/b) or integer (a): ");
fracValue = input.nextLine();
}
//convert to numerator, denominator
int num = 0;
int den = 0;
if (fracValue.contains("/")) {
num = Integer.parseInt(fracValue.substring(0, fracValue.indexOf("/")));
den = Integer.parseInt(fracValue.substring(fracValue.indexOf("/"), fracValue.length()));
} else {
num = Integer.parseInt(fracValue);
den = 1;
}
// return fraction
Fraction fracConv = new Fraction(num, den);
return fracConv;
}
}
substring(int start, int end) includes the character at start and excludes the character at end. Since the integer cannot be parsed with a / in it, you need to do fracValue.indexOf("/")+1 to get just the numerical part of the denominator.
Firstly you have to understand your input
if your input is String a = "6+7", it means your string length is 3, and alloted indexes are 0,1 and 2
where 0 index is '6', 1 index is '+' and 2 index is '7'
So, when you use a.substring(0, a.indexOf("+")) it means you are saying
a.indexOf("+") = 1 index
you should get a string including '0' index but not 1 index, because substring works with inclusive first param and exclusive second param.
In case of this a.substring(a.indexOf("+")+1, a.length())
you don't want to include '+' in your denominator, So you should not include 1 index, that's why you are adding (+1) with indexof.
So, by adding +1 you are saying only pick value from a.indexOf("+") +1, i.e. 2 index,
and length of string is 3, which means you will get string inclusive of 2 index, i.e 7
if your input is "6 + 7" in that case you should use 'trim()' before using Integer.parseInt.

Even or odd. If the number is equal to 0, the program must stop

I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.
Input
1
2
3
0
Output
odd
even
odd
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num;
for (; ; ) {
Scanner reader = new Scanner(System.in);
num = reader.nextInt();
if (num % 2 == 0) {
System.out.println("even");
}
else if(num == 0){
break;
}
else{
System.out.println("odd");
}
}
}
}
The issue with your posted code is addressed in the comment (checking num % 2 == 0 first), but in this case we can improve upon your solution. First, it's "idiomatic" in Java1 to use a while loop with a test after assignment. Second, it's possible to use a ?: conditional operator (a ternary) and remove the remaining if / else. Like,
int num;
Scanner reader = new Scanner(System.in);
while ((num = reader.nextInt()) != 0) {
System.out.println(num % 2 == 0 ? "even" : "odd");
}
1I don't know who defines idioms, but I didn't invent it. And I've seen this construct in JDK source.
int num;
Scanner reader = new Scanner(System.in);
for ( ; ; ) {
num = reader.nextInt();
if (num == 0) {
break;
} else if (num % 2== 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
Your problem is the sequence of your if/else conditions. If the first input is 0, 0 % 2 returns true - so it will never break.
Also, you do not need a new Scanner every time. You can take it out of the loop and reuse it.
You need to check if the value is zero before checking if the value is even.
For example:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num;
while(true) {
num = reader.nextInt();
if(num == 0) break;
else if(num % 2 == 0) System.out.println("even");
else System.out.println("odd");
}
}

How do I simplify this integer validation?

I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.

string index out of bounds exception, on an if else statement

The problem code is below, if you need the entire main method to help me, please ask. The code complies but does not run as expected. I am trying to make the code report back an exclamation mark if the number is out of bounds/larger than the last position of the source text, which is a string the user inputs, so the length cannot be predefined. Exception is 'StringIndexOutOfBoundsException'
TDLR num is an int, sourcetext is a string, both are inputs. Exception: when code should output an '!' instead.
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner sc;
int result, num= 0, end = -2, temp, infolost, count;
String word, sourcetext, answer, space= " ";
String sourcetext2, temp2;
char input, result2, chalost;
sc = new Scanner(System.in);
System.out.println("please enter sourcetext");
sourcetext = sc.nextLine(); // user inputs source text
sourcetext = sourcetext.toLowerCase(); // converts sourcetext into lowercase
System.out.print("Would you like to 1 encrypt, or 2 decrypt?");
answer = sc.next(); // user inputs choice
if (answer.equals("1")||(answer.equals("encrypt"))) {
System.out.println("Please enter at least one word to encrypt");
word = sc.next(); // user inputs one word
for (int i= 0; i < word.length(); i++) {
temp = sourcetext.indexOf(word.charAt(i)); // uses index to convert char positions int num
System.out.print(space + temp + space);
}
System.out.print(space + end);
}
else if (answer.equals("2")||(answer.equals("decrypt"))) {
System.out.println("Please enter digits, with one space between each. End with -2");
while (num > -2) {
num = sc.nextInt(); // num to decrypt
if (num > -2) {
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else if (num > sourcetext.length()) {
System.out.print("!");
} else if (num<0) {
System.out.print("end");
}
}
}
}
}
Try it like this:
int stringLength = sourcetext.length();
if (num > stringLength) {
System.out.print("!");
}
else if (num<0) {
System.out.print("end");
}
This could lead to an IndexOutOfBoundsException - since -1 is greater than -2 - but still out of bounds...
if (num > -2){
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(sourcetext.indexOf(num));
}
Edit: Unless the users input is -2 - the first if-Statement will always run... You probably need to re-work the logic there.
Edit2: If num is -1 sourcetext.charAt(num); leads to an IndexOutOfBounds. Do something like
if(num == -2) {
System.out.print("end");
} else if (num >= 0 && num < sourcetext.lenght()) {
// index ok
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else {
// index out of bounds
System.out.print("!");
}

Digit Adder In Java Not Working

Examples of my output:
123
output: 5
111
output: 2
Lots work but ones like the above don't add correctly... Can anyone point me in the right direction? Here is my code:
import java.util.Scanner;
public class DigitAdder {
public static void main(String [] args) {
int input;
int output = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
input = scan.nextInt();
if(input < 0) {
System.out.println("Enter a positive integer: ");
return;
}
while(input > 1) {
output = output + (input % 10);
input /= 10;
}
System.out.println(output);
}
}
Looks like you're not counting the first digit when your input starts with 1.
Try :
while(input >= 1) {
output = output + (input % 10);
input /= 10;
}

Categories