Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
import java.io.*;
import java.util.*;
public class Binary {
public static void main(String args[]) {
int i = 0, j = 0, num;
Scanner in = new Scanner(System.in);
int arr[] = new int[100];
System.out.println("enter the number");
num = in.nextInt();
while (num != 1) {
j = num % 2;
num = num / 2;
arr[i] = j;
i++;
}
for (i = i; i <= 0; i--) {
System.out.print("The binary number: " + arr[i]);
}
}
}
I wrote this programme to convert decimal input to its corresponding binary value, the programme takes the input but it does not show the output i.e. the binary value. please help
As it was already pointed out, you need to change the condition of
while (num != 1) {
to
while (num > 0) {
since your version is prone to an infinite cycle due to the possibility of num being 2.
Change the for cycle, like this:
for (i = arr.length - 1; i >= 0; i--) {
System.out.print("The binary number: " + arr[i]);
}
but to be able to do this, you need to know how many elements will you need to use, so change the declaration of arr to this
int arr[] = new int[(int)Math.ceil(Math.log(num) / Math.log(2))];
But to be able to do this, you need to initialize num before you declare arr. Code is untested, let me know if there are any typos.
condition should be while(num!=0){ //do calculations}
and change the condition of for loop into for(i=i;i>=0;i--){}
You could use the Integer class and it's static method toBinaryString(int i). This method converts an int into its binary value and returns it as a String.
If I correctly understood what you are trying to achieve, you could just write:
Scanner in = new Scanner(System.in);
System.out.println("enter the number");
int num = in.nextInt();
String binary = Integer.toBinaryString(num);
System.out.print("The binary number: " + binary);
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
There is this program that asks me to write a java program that asks the user to type a positive number n and prints the sum of odd numbers using while loop: 1+3+5+7…+(2n-1).
Example : If the input is 4, then the program will print 16
so what i did is made this code :
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 0;
int sum = 0;
while (i<=n)
{
sum += i ;
i++;
}
System.out.println("Sum = " + sum);
}
}
And the program is not working like how the question wants it to be like
You can use i += 2; which is same as i = i + 2;, instead of using i++;.
But this won't give you the output you expect. So, there has to be made several changes in your code to get the expected result.
First initialise the value of i to 1.
int i = 1;
Then, change the while loop statement to,
while (i <= (2 * n - 1)){
// Your Code
}
Finally, use i += 2; as your increment statement.
The full code is shown below.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 1;
int sum = 0;
while (i<=(2 * n - 1))
{
sum += i ;
i += 2;
}
System.out.println("Sum = " + sum);
}
}
You've initialized i wrong. It should start from 1 since you want to add only odd numbers. Also increase i by 2 units using +=2. Another problem is with the while loop condition. The last number in the sequence will be 2n-1 and not n. So the program will be:
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 1;
int sum = 0;
while (i <= (2 * n - 1)) // Here is the new condition for last number...
{
sum += i ;
i+=2; // Here goes the 2 unit increment...
}
System.out.println("Sum = " + sum);
}
}
You can keep a variable like odd and increase its value by 2 in every iteration.
Also,
you should run the loop less than n times
because you start the loop from 0. Then I hope you will get your desired answer. Here is the sample code which may help you to understand.
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 0;
int sum = 0;
int odd = 1;
while (i<n)
{
sum += odd ;
odd += 2;
i++;
}
System.out.println("Sum = " + sum);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
EDIT: Since there are claims that this is a duplicate question, I will state my stance on why it is not.
The other question had posed a problem regarding the conversion of a string input to an integer (the answer deemed correct). This is irrelevant here, as the problem in my case is one of logic.
The solutions on the other question cannot correct the problem this question presents (finding the syntactical "charAt" error).
Frankly, the context of the other question is beyond the scope of my knowledge in Java.
I have successfully created a program that converts binary numbers to decimal numbers.
import java.util.Scanner;
public class ProblemThree // to convert binary to decimal
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
int[] number = new int[length];
int[] powerTwo = new int[length];
// To list every digit separately //
for (int n = 0; n <= length - 1; n++)
{
number[n] = (int) (binary / Math.pow(10, n)) % 10;
}
// To set the values in powerTwo to 2 //
for (int n = 0; n <= length - 1; n++)
{
powerTwo[n] = 2;
}
// To update the values in powerTwo //
for (int n = 0; n <= length - 1; n++)
{
if (n == 0)
powerTwo[0] = 1;
else if (n == 1)
powerTwo[1] = 2;
else
powerTwo[n] *= powerTwo[n-1];
}
// To add if current value is 1 //
for (int n = 0; n <= length - 1; n++)
{
if (number[n] == 1)
answer += powerTwo[n];
}
System.out.println(powerTwo[0]); // for testing
System.out.println(number[0]); // for testing
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
Seeing how some of the steps were redundant, I tried to simplify the code.
import java.util.Scanner;
public class ProblemThreeTestFunction
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
String number = String.valueOf(binary);
for (int n = 0; n <= length - 1; n++)
{
if (number.charAt(n) == 1)
answer += (int)Math.pow(2, n);
}
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
I actually have no idea why the simplified code logic does not work. It uses the same concept as my original.
Thanks in advanced!
Why don't you just use:
int decimalValue = Integer.parseInt(binary, 2);
But if you use this you Need to use scan.nextLine() not scan.nextInt().
This will just convert your binary number to decimal using base 10 like seen here.
You need to test against the character '1':
if (number.charAt(n) == '1')
not the number 1 that you are currently doing:
if (number.charAt(n) == 1) // WRONG!
Also, since charAt counts from the left, and binary expansion counts from the right, you need to reverse the sense. Change
Math.pow(2, n)
to
Math.pow(2, length - 1 - n)
You are comparing with digit 1, it should be character 1 i.e. '1'.
for (int n = 0; n <= length - 1; n++) {
if (number.charAt(n) == '1') {
answer += (int)Math.pow(2, length - n - 1);
}
}
Also you need to correct the exponent part.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
This code is asking for how many numbers the user will input and then it takes each of those. In the end it should return the smallest value. I know about Math.min methods, I'm just struggling with why the logic below doesn't work, it always prints the last input instead the smallest one.
import java.util.Scanner;
public class Ch5_smallestValue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input how many numbers and then input each one");
int hMany = sc.nextInt();
int firstNum = sc.nextInt();
int smallest = firstNum;
for (int i = hMany; i > 1; i--){
int input = sc.nextInt();
if (smallest < input){
smallest = input;
}
}
System.out.println("smallest = " + smallest);
}
}
Change (smallest < input) to (smallest > input).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am practicing and i need help with this code . I need to read integers from the keyboard and print how many are positive Any help in what im doing wrong in my code below?
int size = 10;
int count = 0;
int cuenta = 0;
int[] numbers = new int[size];
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter 10 digits: ");
while (count < size) {
numbers[count] = keyboard.nextInt();
count++;
}
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 0) {
cuenta++;
System.out.println("There are " + cuenta);
}
}
}
}
You have your logic to check for positive integers right. To point you in the right direction think about your print statement and whether it need to be within the for loop.
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 0) {
cuenta++;
System.out.println("There are " + cuenta);
}
}
you need to print out the count after for loop so that it has right answer
System.out.println("There are " + cuenta);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Good day sir. My teacher told us to take all the even numbers from the input file. But the even number keeps telling me that it's 23 evens and it should be 8 and 66.67%. My input from file is:
5 7 2 8 9 10 12 98 7 14 20 22 (with white spaces)
and my code is:
import java.io.*;
import java.util.*;
public class number2 {
public static void main (String[] args) throws FileNotFoundException{
Scanner input = new Scanner(new File("number.txt"));
int sum = 0;
int count = 0;
int evenCount = 0;
float percent = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
sum+=num;
count++;
evenCount = evenNumber(num, count);
}
percent = (evenCount*100)/count;
System.out.println("\n" +count + " Numbers, " + "Sum = " +sum);
System.out.println( evenCount + " evens " +"(" + percent +"%)");
}
public static int evenNumber(int counter, int number){
if(number%2==0)
counter++;
return counter;
}
}
I think you're calling the evenNumbermethod with the switched parameters...
while(input.hasNextInt()){
int num = input.nextInt();
sum+=num;
count++;
//first parameter is number read from file, second parameter is the current count
evenCount = evenNumber(num, count);}
//...
On your method evenNumbermethod signature you have
//first parameter is the counter, second parameter is the read number
public static int evenNumber(int counter, int number)
You should switch the parameters being called inside the evenNumbermethod in the while block:
evenCount = evenNumber(evenCount, num)
Also, you should pass evenCountto the evenNumbermethod instead of count, otherwise you will be increasing the count of all numbers instead the count for only even numbers.