I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand.
What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages:
The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
Multiple markers at this line
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable Binary
Multiple markers at this line
Syntax error on token "mod", invalid AssignmentOperator
Syntax error on token "mod", invalid AssignmentOperator.
Integer.toBinaryString(int) should do the trick !
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.
Working code :
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.
There are a two main issues you need to address:
Don't declare a method inside another method.
Your loop will never end.
For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.
For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation:
int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.
For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.
mod is not a valid operator, the syntax you wanted was %
You can use System.out.print to print on the same line rather than println
Try these corrections and let me know how you get on:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
Here is a small bittesting code I made for Android.
int myres = bitTest(7, 128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards
Mikael Andersson
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}
Related
The problem I'm trying to solve comes from ProjectEuler.
Some integers have following property:
n + reverse(n) = a number consisting entirely of odd digits.
For example:
14: 14 + 41 = 55
Numbers starting or ending with 0 aren't allowed.
How many of these "reversible" numbers are there below 10^9?
The problem also gives a hint:
there are 120 such numbers below 1000.
I'm quite new to Java, and I tried to solve this problem by writing a program that checks all the numbers up to a billion, which is not the best way, I know, but I'm ok with that.
The problem is that my program gives out a wrong amount of numbers and I couldn't figure out why! (The code will most likely contain some ugly things, feel free to improve it in any way)
int result = 0;
boolean isOdd = true;
boolean hasNo0 = true;
public int reverseNumber(int r) //this method should be working
{ //guess the main problem is in the second method
int n = 0;
String m = "";
if (r % 10 == 0) { hasNo0 = false; }
while (r > 0){
n = r % 10;
m = String.valueOf(m+n);
r /= 10;
}
result = Integer.parseInt(m);
return result;
}
public void isSumOdd(int max)
{
int number = 1;
int sum = 0;
Sums reverseIt = new Sums();
int amount = 0;
while (number <= max)
{
sum = reverseIt.reverseNumber(number) + number;
while (sum > 0)
{
int x = sum % 10;
if (x % 2 == 0) { isOdd = false; }
sum /= 10;
}
if (isOdd && hasNo0) { amount++; }
number++;
isOdd = true;
hasNo0 = true;
}
System.out.println(amount);
}
Called by
Sums first = new Sums();
first.reversibleNumbers(1000000000);
The most important problem in your code is the following line:
sum = reverseIt.reverseNumber(number) + number;
in isSumOdd(int max) function. Here the reverseIt object is a new instance of Sums class. Since you are using Sums member data (the boolean variables) to signal some conditions when you use the new instance the value of these member variables is not copied to the current caller object. You have to change the line to:
sum = this.reverseNumber(number) + number;
and remove the Sums reverseIt = new Sums(); declaration and initialization.
Edit: Attempt to explain why there is no need to instantiate new object instance to call a method - I've found the following answer which explains the difference between a function and a (object)method: https://stackoverflow.com/a/155655/25429. IMO the explanation should be enough (you don't need a new object because the member method already has access to the member data in the object).
You overwrite odd check for given digit when checking the next one with this code: isOdd = false;. So in the outcome you check only whether the first digit is odd.
You should replace this line with
idOdd = idOdd && (x % 2 == 0);
BTW. You should be able to track down an error like this easily with simple unit tests, the practice I would recommend.
One of the key problems here is that your reverseNumber method does two things: check if the number has a zero and reverses the number. I understand that you want to ignore the result (or really, you have no result) if the number is a multiple of 10. Therefore, you have two approaches:
Only send numbers into reverseNumber if they are not a multiple of 10. This is called a precondition of the method, and is probably the easiest solution.
Have a way for your method to give back no result. This is a popular technique in an area of programming called "Functional Programming", and is usually implemented with a tool called a Monad. In Java, these are implemented with the Optional<> class. These allow your method (which always has to return something) to return an object that means "nothing at all". These will allow you to know if your method was unable or unwilling to give you a result for some reason (in this case, the number had a zero in it).
I think that separating functionnalities will transform the problem to be easier. Here is a solution for your problem. Perhaps it isn't the best but that gives a good result:
public static void main(final String [] args) {
int counter = 0;
for (int i = 0; i < 20; i++) {
final int reversNumber = reverseNumber(i);
final int sum = i + reversNumber;
if (hasNoZeros(i) && isOdd(sum)) {
counter++;
System.out.println("i: " + i);
System.out.println("r: " + reversNumber);
System.out.println("s: " + sum);
}
}
System.out.println(counter);
}
public static boolean hasNoZeros(final int i){
final String s = String.valueOf(i);
if (s.startsWith("0") || s.endsWith("0")) {
return false;
}
return true;
}
public static int reverseNumber(final int i){
final StringBuilder sb = new StringBuilder(String.valueOf(i));
return Integer.parseInt(sb.reverse().toString());
}
public static boolean isOdd(final int i){
for (final char s : String.valueOf(i).toCharArray()) {
if (Integer.parseInt(String.valueOf(s))%2 == 0) {
return false;
}
}
return true;
}
the output is:
i: 12
r: 21
s: 33
i: 14
r: 41
s: 55
i: 16
r: 61
s: 77
i: 18
r: 81
s: 99
4
Here is a quick working snippet:
class Prgm
{
public static void main(String args[])
{
int max=(int)Math.pow(10, 3); //change it to (10, 9) for 10^9
for(int i=1;i<=max;i++)
{
if(i%10==0)
continue;
String num=Integer.toString(i);
String reverseNum=new StringBuffer(num).reverse().toString();
String sum=(new Long(i+Long.parseLong(reverseNum))).toString();
if(sum.matches("^[13579]+$"))
System.out.println(i);
}
}
}
It prints 1 number(satisfying the condition) per line, wc is word count linux program used here to count number of lines
$javac Prgm.java
$java Prgm
...//Prgm outputs numbers 1 per line
$java Prgm | wc --lines
120
I am having trouble finding a formula or finding the right conditionals to use when passing an array of integers and determining the minimum number of bits to store the signed integer.
I have done the reverse to find the range of integers (min to max) given number of bits using equations:bits b: max = -2^(b-1) min = 2^(b-1)-1
Thanks for your help!
public static void main(String[] args)
{
int[] intAr = {2,15,16,100,1000,999999};
printMinBits(intAr);
}
public static void printMinBits(int[] y)
{
System.out.print("\n min bits\nnumber to store\n");
for(int n = 0; n < y.length; n++)
{
System.out.printf("%6d",y[n]);
/*MISSING*/
System.out.println("");
}
}
Output for min bits should be: 3,5,6,8,11,21 (in a table)
Integer class has builtin bit counting, and positioning methods. Simple math to get the highest bit position, and therefor minimum bits needed:
private static int minBitsNeeded(int i) {
return 1 + Integer.SIZE - Integer.numberOfLeadingZeros(i);
}
So to fill in MISSING in your example:
public static void printMinBits(int[] y)
{
System.out.print("\n min bits\nnumber to store\n");
for(int n = 0; n < y.length; n++)
{
System.out.printf("%6d",y[n]);
System.out.printf( "%15d\n", minBitsNeeded(y[n]) );
}
}
This method can be used to find the minimum bits required to store a signed integer
public static int minBits(int n) {
int b = 1;
//If n is negative
if(n < 0) {
n *= -1;
}
while (n > 0) {
n /=2;
b++;
}
}
As far as I can tell, you need a function to get the bit count for a given int. You could do that with Integer.toBinaryString(int) and something like
private static int getBitCount(int v) {
String str = Integer.toBinaryString(v);
int count = 0;
for (char ch : str.toCharArray()) {
if (ch == '0') {
count++;
} else {
break;
}
}
return 1 + str.length() - count;
}
Then you could print your table with formatted io and a for-each loop. Something like
public static void printMinBits(int[] y) {
System.out.println("Number to store\t\tMin bits");
for (int v : y) {
System.out.printf("%d\t\t\t%d%n", v, getBitCount(v));
}
}
Which I executed with your provided main to get
Number to store Min bits
2 3
15 5
16 6
100 8
1000 11
999999 21
Im having trouble converting binary to a decimal. We have to use a function for the conversion and do it by hand rather than use a predefined function. This is what I have so far, I know it is a mess but I am stuck on how to fix it. Thanks!
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
To use a function, as your assignment requires, you have to write the function outside the main method, and then include a statement that calls the function. So move this above the line that says public static void main:
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, each function or method (including main) has its own variables that it uses, called local variables; but the local variables that each function uses are its own separate copies. Thus, the above function won't be able to use the binaryLength or decimal variabes belonging to main. You'll need to declare them inside binaryToDecimal:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, this function won't be able to access main's inString, but the idea is that you've given the function the string you want to work with, which it refers to as binaryString. So change inString to binaryString in the function:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal = decimal + Math.pow(2,binaryString.length() - 1 - i);
}
return (int) decimal;
}
And also note that the binaryLength and decimal variables are totally unrelated to the variables of the same name in main. That means that when you assigned binaryLength in main, that has no effect on binaryLength in binaryToDecimal. You'll need to assign it in the function. Change int binaryLength; to
int binaryLength = binaryString.length();
Finally, in order to use the function, main will need to call it. Put this in the main function:
decimal = binaryToDecimal(inString);
When main executes that, it will call the function and tell it to work with inString. The function will call that binaryString, though. The function will return a result, and then main will assign that result to the variable decimal--that means the local variable decimal that belongs to main, since the above statement is inside main.
I don't know if this will make your whole program work. (It should, but I'm not sure.) But I'm just trying to explain the details of how to use functions.
The confusing part is with the Math.pow, and its complicated arguments, where off-by-one errors are easily made.
Yet, if we have a number at base 10, like
123
its value is
(((0*10)+1)*10+2)*10+3
This looks complex, but note the easy pattern: Starting out with 0, we go through the digits. As long as we have another dgit, we multiply the previous result by the base and add the digit value. That's all! No Math.pow, no complex index calculations.
Hence:
String s = "1010";
int value = 0;
int base = 2;
for (i=0; i < s.length(); s++) {
char c = s.charAt(i);
value = value * base;
value = value + c - '0';
}
When I cleaned up your code, it worked just fine -
public static int binaryToDecimal(String binaryString) {
int binaryLength = binaryString.length();
int decimal = 0;
for (int i = binaryLength - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength - 1 - i);
}
}
return decimal;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String inString = input.nextLine();
while (!"-1".equals(inString)) {
System.out.println(binaryToDecimal(inString));
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Output
Enter a binary number:
01
1
Enter a binary number:
10
2
Enter a binary number:
-1
All set !
Here's the function after a little clean up.
public static int binaryToDecimal (String binaryString) {
int decimal = 0;
int base = 2;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal += Math.pow(base,i);
}
return decimal;
}
I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */
I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)