This question already has answers here:
Converting Decimal to Binary Java
(26 answers)
Closed 6 years ago.
Okay I know there is already a lot of solutions for this title. I have gone through those links but didn't help
I am new to java and I am writing one simple decimal to binary conversion program. In which a user will input the decimal number base 10 and get the output in binary form base 2.
I have already written a program but I am not getting the proper output. Something is missing which I am unable to identify.
Here is my code
import java.util.Scanner;
class BinaryConversion{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the decimal number to convert into binary");
int num = scan.nextInt();
StringBuilder BinaryString = new StringBuilder();
BinaryString.setLength(0);
while(num!=1){
num/=2;
int r = num%2;
BinaryString.append(Integer.toString(r));
}
System.out.println(BinaryString.reverse());
}
}
In the above program If I enter the decimal number let's say 95 the output should be 1011111.
But I am getting 101111
Please help.
You are stopping when num equals 1. And doing the division at first would miss one binary digit.
while(num!=1){
num/=2;
int r = num%2;
BinaryString.append(Integer.toString(r));
}
would be:
while (num > 0) { // till the remaining is greater than zero
int r = num % 2; // at first fetching the modulus result
BinaryString.append(Integer.toString(r));
num /= 2; // then dividing
}
Related
So I'm currently a beginner programmer trying to slove some basic programming tasks. But I dont understand why My code is wrong. In eclipse everyting works. It's a coding problem from codewars.com
Introduction:
You ask a small girl,"How old are you?" She always says, "x years old", where x is a random number between 0 and 9.
Write a program that returns the girl's age (0-9) as an integer.
Assume the test input string is always a valid string. For example, the test input may be "1 year old" or "5 years old". The first character in the string is always a number.
package headfirstjava;
import java.util.Random;
public class do_something5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
{
int min =1;
int max =9;
int age1 = (int)Math.round(Math.random() * (max - min)+ min);
int age2 = (int)Math.round(Math.random() * (max - min + 1)+ min);
System.out.println("I'm "+ age1+ " Old");
}
}
}
I think you didn't understand the problem asked. Here the input of the program is the string "x years old" and you have to return "x" as an integer :
return Integer.parseInt(input.substr(0,1))
I am not sure what the problem is.
Try this if the problem is with generating random number:
// create random object
Random ran = new Random();
// Print next int value
// Returns number between 0-9
int nxt = ran.nextInt(10);
// Printing the random number
// between 0 and 9
System.out.println
("Random number between 0 and 9 is : " + nxt);
Also check out Random class in java! (Sry if this doesn't help)
If you simply want to extract a number from a specific string format (means you know where the number you are looking for is) use the Character.getNumericValue(string.charAt(0)) method.
Scanner scanner = new Scanner(System.in)
System.out.println("How old are you?");
String s= scanner.nextLine();
char c=s.charAt(0);
System.out.println("1st character is: "+ Character.getNumericValue(c) );
This is the simplest form that you can go. I suggest you go through w3schools.com for the basics.
This question already has answers here:
Mod in Java produces negative numbers [duplicate]
(5 answers)
Closed 3 years ago.
Sorry im just learning java and im new to coding!
The task of my code is to evaluate input in terms of odd and even numbers.
Without the math.abs line the code would not recognize the odd/even values of negative numbers correctly.
i made a fix using the math.abs command to convert the negative value and get the desired result. But, i just wanted to know why this step is necessary and how java scanner interprets the negative value/symbol and provides the wrong answer without my fix.
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a number: ");
int x = Integer.parseInt(reader.nextLine());
int f = Math.abs(x);
if ( f % 2 == 1){
System.out.println("The number is odd.");
}
else {
System.out.println("The number is even.");
}
}
}
The remainder of a negative number divided by a positive number will be negative.
-1 % 2
is
-1
but since that is not 1, you will declare it to be even.
This question already has answers here:
How to format a Java string with leading zero? [duplicate]
(24 answers)
Closed 5 years ago.
So my program is meant to take user input which is supposed to be a number from 1-511. Once the number is entered my program uses Integer.toBinaryString(); to turn their number into the binary form of that number. Then, if the binary output is not 9 digits, I want to fill the rest of that binary number with 0's until its 9 digits long. So I use an if statement to check if the length of the binary is less than 9, if it is I have it set to subtract 9 from binary.length so we can know how many zeros we need to add. Im currently stuck so I just made a print statement to see if its working so far and it does. But im not sure what to do as far as finishing it.
import java.util.Scanner;
public class Problem8_11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter one number between 0 and 511: ");
int number = input.nextInt();
int binaryZeros = 9;
String binary = Integer.toBinaryString(number);
if(binary.length() < 9) {
int amountOfZeros = 9 - binary.length();
System.out.print(amountOfZeros);
}
}
My question: How do I add the zeros to binary?
Presumably you want to prepend the zeros. There are many ways to do this.
One way:
StringBuffer sb = new StringBuffer( Integer.toBinaryString(number) );
for ( int i=sb.length(); i < 9; i++ ) {
sb.insert( 0, '0' );
}
String answer = sb.toString();
Be sure to handle the case where the number cannot be parsed into an integer.
This question already has answers here:
How to get the separate digits of an int number?
(32 answers)
Closed 6 years ago.
I just started learning Java (two months and counting), and I still have lots of questions and a whole lot to learn. Right now I want to use the Scanner class to "divide" an integer into its digits. I'll explain myself better with an example:
I request the user to type a four-digit integer, say 8919. What I want to do is to use the Scanner class to divide that integer and to assign each one of its digits to a variable; i.e. a = 8, b = 9, c = 1 and d = 9.
I positively know that it can be done and that the Scanner class is the way to go. I just don't know how to properly use it. Can a noob in need get some help here? Thanks!
EDIT:The suggestion that has been made does not match my specific question. In that thread the class Scanner is not used to separate the integer into digits. I specified i wanted to use the Scannerclass because many different methods used there are still way beyond my level. Anyway, there are lots of interesting ideas in that thread that i hope i will be able to use later, so thanks anyway.
You can use a delimiter with the scanner. You can use an empty string as delimiter for this case.
String input = "8919";
Scanner s = new Scanner(input).useDelimiter("");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
d = s.nextInt();
s.close();
you should read the integer as whole number and store it in a variable. after you stored it you can split it up. other way is so store it as string and then split the string. what you should choose depends on what youwant to do with it afterwards
Try this:
import java.util.Scanner;
public class ScannerToTest {
public static void main(String[] args) {
int a,b,c,d;
System.out.print("Please enter a 4 digit number : ");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
String numberToString = String.valueOf(number);
if(numberToString.length() == 4) {
String numberArray [] = numberToString.split("");
a = Integer.parseInt(numberArray[1]);
b = Integer.parseInt(numberArray[2]);
c = Integer.parseInt(numberArray[3]);
d = Integer.parseInt(numberArray[4]);
System.out.println("Value of a is : " + a);
System.out.println("Value of b is : " + b);
System.out.println("Value of c is : " + c);
System.out.println("Value of d is : " + d);
}else {
System.out.println("Numbers beyond 4 digits are disallowed!");
}
}
}
This program should count amount of digits in a number.
Here is my code:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
Scanner marty = new Scanner(System.in);
float sk;
System.out.println("Enter start number: ");
sk = marty.nextFloat();
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);
marty.close();
}
}
I am getting this kind of error, while tryin to input number with 4 or more digits before comma, like 11111,456:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at Converter.main(Converter.java:11)
Any ideas about what the problem may be?
Taking the log (base10) of a number and adding 1 is not going to give you the correct answer for the number of digits of the input number anyway.
Your given example of 11111.465 has 8 digits. The log10 of this number is 4.045... adding 1 gives you the answer of 5.
Another example: 99, Log10(99) = 1.99, cast as int = 2, add 1 = 3... clearly is only 2 digits.
You could just read the input as a String then do something like the following instead
int count = 0;
String s = /* (Input Number) */
for(char c : s.toCharArray())
{
if(Character.isDigit(c))
count++;
}
You would have to also have to check it is actually a number though by checking its pattern...
When inputting a number, you aren't supposed to include commas unless you expect to split it. If you want a decimal, use a "." instead. If you want a number greater than 999, don't include a comma
Like many people have said, the comma is messing you up.
One option you may consider if your input needs comma is replacing the commas from the input string before try to count the number of digits.
System.out.println("Enter start number: ");
String input = marty.nextLine();
float sk = Float.parseFloat(input.replace(",", ".")); // use input.replace(",", "") if you want to remove commas
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);