Number to Binary to Zero Counter [duplicate] - java

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.

Related

Give a random age number between 0-9 Java

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.

How can i input multiple times in one line? [duplicate]

This question already has answers here:
How to read multiple Integer values from a single line of input in Java?
(21 answers)
Closed 1 year ago.
How can I input multiple times in one line?
public class Awit {
static void numbers(){
Scanner user = new Scanner(System.in);
int arraylist[] = new int [5];
System.out.println("Enter five integers:");
System.out.print("");
for(int i = 0; i<=4; i++){
arraylist[i] = user.nextInt();
}
public static void main (String []args){
numbers();
}
}
Output:
Enter five integers:
1
2
3
4
5
I want the output to be like this
1 2 3 4 5
The program that you have written will read multiple numbers from a line ... if you give it multiple numbers on a line.
$ java Awit.java
Enter five integers:
1 2 3 4 5
$
The only issues with the code you have written are:
it is missing an import for Scanner, and
there is a } missing at the end of your numbers method.
Those problems will give compilation errors. Assuming that you correct them, you will not get any output (apart from the prompt to enter some numbers) because your program doesn't print the array(!)
If you want to know how to print the numbers, read the following:
What's the simplest way to print a Java array?

Why is was my code not performing with negative values inputted? [duplicate]

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.

Program Decimal to Binary Conversion error in output [duplicate]

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
}

hasNext() of Scanner keeps looping [duplicate]

This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.

Categories