I need to write a program that can convert bits into decimal. Whenever I enter a bit, it only outputs 0.0. I cannot figure out why. I know it's incredibly simple but I am just not seeing it. Any help would be appreciated.
import java.lang.Math;
import java.util.Scanner;
public class Lab1 {
static double number = 0;
public static double toDec(String num) {
char[] charArray = num.toCharArray();
for(int i = 0; i<charArray.length;i++) {
if(charArray[i] == 1) {
number = Math.pow(2, charArray.length-i);
}
}
return number;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int bit;
String bitString;
System.out.println("Please enter a bit");
bit = keyboard.nextInt();
bitString = Integer.toString(bit);
System.out.println(toDec(bitString));
}
}
You have compared charArray[i] to 1, but you're comparing apples to oranges, specifically, a char to an int.
Compare to the char '1' instead.
if(charArray[i] == '1') {
Also, you can make number a local variable in toDec; it doesn't need to exist outside that method.
In addition, this will only work if one bit is set. Right now you are working with one bitonly, but if you want to modify this to work with multiple bits, another changes is needed.
You overwrite number each time toDec is called and the condition is true. You will probably want to add to number with += instead of overwriting the previous value with =.
Integer#parseInt(String str, int radix) does the job :
public static Integer toDec(String num) {
return Integer.parseInt(num, 2);
}
So if you want to take the String "110011" which is 51. For big-endian you are going to have to determine how many bits to process. So if you read the string and it is 6 digits long then you know the first bit has to be shifted 6 places to the left.
int l = 6;
long value = 0;
for( int i = 0; i < l; i++ )
{
int bit = ( charArray[i] == "1" ) ? 1 : 0;
l = l + ( bit << l-i );
}
For float you would basically have to build an interpreter to decode the bits based on however the float is represented in binary.
Related
This question already has answers here:
How to convert a Binary String to a base 10 integer in Java
(12 answers)
Closed 4 years ago.
Main:
public class Main{
public static void main(String[] args){
System.out.println(Convert.BtoI("101101010101"));
System.out.println(Convert.BtoI("1011110"));
}
}
Sub:
public class Convert{
public static int BtoI(String value){
int no = 0;
for(int i=value.length()-1;i>=0;i--){
if(value.charAt(i)=='1')
no += (???) ;
++;
}
return no;
}
}
How can I convert a string binary to integer without using maths.pow, just using + - * and /, should I implement another for loop for it is int j = 1;i <= example; i*=2){ ?. I am quite confused and want to learn without the usage of maths.pow or any similar codes.
From the beginning of the string until to the end you can just multiply each character with its power and sum up the total which gives you the base ten value:
public static int binaryToInt(String binaryNum) {
int pow = 1;
int total = 0;
for (int i = binaryNum.length(); i > 0; i--) {
if (binaryNum.charAt(i-1) == '1') {
total += pow;
}
pow *= 2;
}
return total;
}
But i think this is way more elegant:
String binaryNum = "1001";
int decimalValue = Integer.parseInt(binaryNum, 2);
How about Integer.parseInt(yourString,2); ?? 2 means you are parsing base2 number.
Starting from your code + some vital style changes:
public class Convert {
public static int binaryToInt(String value) {
int no = 0;
for (int i = 0; i < value.length() - 1; i++) {
no = no * 2; // or no *= 2;
if (value.charAt(i) == '1') {
no = no + 1; // or no++
}
}
return no;
}
}
The meaning of the code I added should be self-evident. If not, I would encourage you to work out what it does as an exercise. (If you are not sure, use a pencil and paper to "hand execute" it ...)
The style changes (roughly in order of importance) are:
Don't start a method name with an uppercase character.
Use camel-case.
Avoid cute / obscure / unnecessary abbreviations. The next guy reading your code should not have to use a magic decoder ring to understand your method names.
Put spaces around operators.
4 character indentation.
Put spaces between ) and { and before / after keywords.
Use curly brackets around the "then" and "else" parts of an if statement, even if they are not strictly necessary. (This is to avoid a problem where indentation mistakes cause you to misread the code.)
I have the correct code, I found an answer long ago, however I still don't understand why it works.
class Main {
public static void main(String[] args) {
System.out.println(D5PSum(10));
}
private static int D5PSum(int number) {
String n = Integer.toString(number);
int sum = 0;
for (int i = 0; i < n.length(); i++) {
// (1) WHY DOES THIS NOT WORK
//sum += Integer.parseInt(number.charAt(i));
// (2) MORE IMPORTANTLY WHY DOES THIS WORK
char c = n.charAt(i);
sum += (c-'0');
// (3) WHAT IN THE WORLD IS c-'0'
}
return sum;
}
}
// (1) WHY DOES THIS NOT WORK
because Integer.parseInt(...); is expecting a string as parameter not a char
// (2) MORE IMPORTANTLY WHY DOES THIS WORK
char c = n.charAt(i);
any char is nothing else as an integer mapped to a table of symbols...(ASCII table for example) so this (c - '0') is just another valid mathematical operation
charAt is not a valid method of the primitive type int.
'0' is the character 0, and the character encoding set that Java uses has 0 to 9 in a consecutive block. Therefore c - '0' yields the position of c in that consecutive block which is therefore the value of the digit. (Actually this sort of thing is idiomatic C - goes right back to the 1960s).
You should first convert String to Int.. Please check the below code:
class MainClass {
public static void main(String[] args) {
System.out.println(D5PSum(11));
}
private static int D5PSum(int number) {
String n = Integer.toString(number);
System.out.println(n);
int sum = 0;
for (int i = 0; i < n.length(); i++) {
// (1) WHY DOES THIS NOT WORK
String str = String.valueOf(n.charAt(i));
sum += Integer.parseInt(str);
// (2) MORE IMPORTANTLY WHY DOES THIS WORK
// char c = n.charAt(i);
// sum += (c-'0');
// (3) WHAT IN THE WORLD IS c-'0'
}
return sum;
}
}
1
It doesnt work because Integer.parseInt takes a String and String.charAt returns a char(actar). Integer.parseInt (Character.toString(n.charAt(i))) would Work.
2/3
A char represents a number between 0 and 65535. EACH digit-characters (0-9) has a number in that range which depends on the charset. All digits are typically in a row, for example the character 0 has the value 48, 1 49 and 9 57. So ich you want to know the digit value of a char you simply subtract the character value of 0 from your character. That is the Line c-'0'
// (1) WHY DOES THIS NOT WORK
//sum += Integer.parseInt(number.charAt(i));
number is a variable of primitive data type "int" so number.charAt(i) won't work.
// (2) MORE IMPORTANTLY WHY DOES THIS WORK
char c = n.charAt(i);
n is an instance of String and we are getting the character at i th position in the n string
sum += (c-'0');
// (3) WHAT IN THE WORLD IS c-'0'
for every character there is an ascii code assigned. '0' = 48, 'c' = 99. That's the reason why it works here. when 'c'-'0' is executed, it's equivalent to 99-48
Why convert to a string in the first place? The simplest and fastest way to solve this is without deviation to strings:
private static int D5PSum(int number) {
int v = number, sum = 0;
while (v != 0) {
sum += v % 10;
v /= 10;
}
return sum;
}
If you want your code (the part which does not works to work then do this).
class Main {
public static void main(String[] args) {
System.out.println(D5PSum(10));
}
private static int D5PSum(int number) {
String n = Integer.toString(number);
int sum = 0;
for (int i = 0; i < n.length(); i++) {
sum += Integer.parseInt(n.charAt(i)+"");
}
return sum;
}
}
To get sum of the digits of a string str:
int sum = str.chars().map(Character::getNumericValue).sum();
I am trying to apply a simple binary addition algorithm in Java, but I am getting errors repeatedly. Could anyone please help me. Thanks!
public class BasicBinaryAddition {
public static void main(String[] args)
{
int []sum = new int [3];
int []a = {0,1,0};
int []b = {1,1,0};
int carry =0;
int bitIndex;
for (bitIndex =0; bitIndex < a.length; bitIndex++)
{
int bitSum = a[bitIndex] + b[bitIndex] + carry;
sum[bitIndex] = bitSum%2;
double d = bitSum/2;
carry = (int) Math.floor(d);
}
sum[bitIndex] = carry;
for (int i = 0 ; i <= sum.length-1; i++)
System.out.print(sum[I]+"");
}
}
Your sum array is too short to hold the full result. Make it length 4, this will avoid the ArrayIndexOutOfBoundsException.
The way you calculate the carry could also be simplified to
carry = bitSum / 2;
This is an integer division and yields an integer result.
Adding two 3-bit numbers could result in 4 bits. So, you should declare
int []sum = new int [4];
Also, you should use small i in the last for-loop
System.out.print(sum[i]+"");
You should put (sum[bitIndex] = carry) inside the loop;
public class BasicBinaryAddition {
public static void main(String[] args)
{
int []sum = new int [3];
int []a = {0,1,0};
int []b = {1,1,0};
int carry =0;
int bitIndex;
for (bitIndex =0; bitIndex < a.length-1; bitIndex++)
{
int bitSum = a[bitIndex] + b[bitIndex] + carry;
sum[bitIndex] = bitSum%2;
double d = bitSum/2;
carry = (int) Math.floor(d);
sum[bitIndex] = carry;
}
for (int i = 0 ; i <= sum.length-1; i++)
System.out.print(sum[I]+"");
}
}
This looks like homework so I will just point you in the right direction.
The first problem is in your line:
System.out.print(sum[I]+"");
You are using "I" instead of "i" so the compiler is upset that it can't find a variable "I".
The second problem is that you have an overflow problem. If you add 2 binary numbers of length 3 it is possible to have an answer that is 4 bits long.
101 + 100 = 1001
When you perform the line: sum[bitIndex] = carry, bit index equals 3, which means the 4th item of the array sum (remember Java arrays start from index 0). However sum is declared to be of length 3, so Java's head explodes in rage that you tried to access an element of an array that is out of bounds. The answer to this problem is to declare sum to be of length 4.
Another thing that can be cleaned up are the lines:
double d = bitSum/2;
carry = (int) Math.floor(d);
This can be simplified to:
carry = bitSum/2;
This works because carry and bitSum are both integers, so Java will perform integer division, which just ignore anything that would happen after the decimal in regular division.
I'm trying to create a Java program that converts a String into an Integer recursively. This is currently what I have but it gives me an error, "Exception in thread "main" java.lang.NumberFormatException". The method is supposed to take in a number in the form of a string then iterate through each position. Through each iteration it turns the single number into a integer and adds it to x. By the end of it x is suppose to have the String number in integer form.
import java.util.Scanner;
public class Problem{
public static int x=0;
public static int integer;
public static int intconvert(String numb,int index,int times){
if(index==numb.length()){
return x;
}
else{
integer=Integer.parseInt("numb.charAt(index)"); //
x+=integer*times; //add int and multiply it
return intconvert(numb, index++, times*10); //
}
}
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.print("Enter the String digit: ");
String number=scan.nextLine();
intconvert(number, 0, 1);
/* System.out.println(number.charAt(0));
System.out.println(number.charAt(1));
System.out.println(number.charAt(2));*/
}
}
Even if the method was correct, i.e:
public static int intconvert(String numb, int index, int times) {
if (index == numb.length()) { return x; }
integer = Integer.parseInt(String.valueOf(numb.charAt(index))); //
x += integer * times; // add int and multiply it
return intconvert(numb, index++, times * 10); //
}
You'll still get an StackOverFlow exception, because you of the way you increment your x, it will never enter the stopping condition.
If I understood what you wanted to do, the solution is:
public class Cenas {
public static int x = 0;
public static int integer;
public static int intconvert(String numb, int index, int times) {
integer = Integer.parseInt(Character.toString(numb.charAt(index))); //
x += integer * times; // add int and multiply it
if (index == 0) { return x; }
return intconvert(numb, --index, times * 10); //
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the String digit: ");
String number = scan.nextLine();
System.out.println(intconvert(number, number.length() - 1, 1));
}
Start at the algarism with the less weight and work your way to the beggining index, also you were missing the print statement at your main call.
Because you are incrementing your "times" 10 times by each iteration you must start ate the last index of the string.
Example:
123 = 1 * 100 + 2 * 10 + 3 * 1
Your problem was not recursion but the algorithm you were using.
The line
integer=Integer.parseInt(numb.charAt(index));
won't work, because charAt() returns a char, and parseInt expects a String. Try converting that char into a String with Character.toString(c):
Integer.parseInt(Character.toString(numb.charAt(index)))
Add
integer = Integer.parseInt(numb.substring(index, index + 1)); //
index++;
Instead of:
integer=Integer.parseInt("numb.charAt(index)");
And remove ++ of index++ from return intconvert(numb, index++, times * 10); its not increase passed index.
Numbers are sequential in their ascii values, so in order to turn your char into an int, you could simply do:
int integer = numb.charAt(index) - '0';
all that is left is to ensure that integer is between bounds and your function should work just fine.
by the way, I would remove the static global variables. If you simply pass them as parameters instead, your solution will be "pure", as in side-effect free or referentially transparent
Try changing
integer=Integer.parseInt("numb.charAt(index)");
into
integer=Integer.parseInt(numb.substring(index, index + 1));
The original line tries to find a number within the string "numb.charAt(index)", which doesn't contain any numbers.
Also, change index++ to index + 1 or even ++index, since index++ has no effect in this case (it only increments index after it's been used, and just before it goes out of scope.
I'm tring to assign variables dynamically, but I don't have a clue how to do that.
What my program should do:
"Write a program to have the user enter three lengths of sides and determine whether the figure is a triangle or not."
This is what I have so far:
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
double z;
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z = Double.parseDouble(x.substring((y + 1), i));
y = i;
a += z;
}
}
}
}
What I would love to do would be to have this in the if statement:
int a++;
z(a) = Double.parseDouble(x.substring((y + 1), i));
But as I have found out this will not work and I need some kind of array. Sadly, my online class has not started arrays yet and I haven't gotten a grasp of them yet in my own learning.
I would like to make 3 variables (z1, z2, z3) and assign an integer to each one within the if statement.
Edit:
Here's some revised code that now works how I wanted now. Hope this helps someone else in the future!
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
Double[] z = new Double[3];
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z[a] = Double.parseDouble(x.substring((y + 1), i));
y = i;
a++;
}
}
//Some test code to see if it was working
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(z[2]);
}
}
You don't need to use arrays, especially that you haven't been introduced to them. You can simply use a Scanner class, and do something similar to
Scanner in = new Scanner(System.in); // this will read from the standard system input
System.out.println("Please enter three lengths of sides: ");
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
And write some logic (I guess that's the point of your homework) checking if this figure is a triangle.
In case you would like to use arrays , you could declare one by doing:
int[] sidesLenghtsArray = new int[3];
And then instead of refering to three different int variables, you could simply refer to your array elements:
int[0] = in.nextInt();
int[1] = in.nextInt();
int[2] = in.nextInt();
Just remember - the number in the brackets is the number of elements that your array will have, but refering to that elements, you start counting from 0. That's why we start with int[0] (1st element) and end with int[2] (3rd element).
Java does not support tuple assignment like
def (a,b,c) = "1,2,3".split(",")
It is possible to do this in Java 8 with a following code:
int[] abc = Arrays.stream("1,2,3".split(",")).mapToInt(Integer::parseInt).toArray();
Here, a would be abc[0], b is abc[1].
Similar code in Java 7 could be this:
String[] abc = "1,2,3".split(",");
int a = Integer.parseInt(a[0]);
int b = Integer.parseInt(a[1]);
int c = Integer.parseInt(a[2]);
The very basic idea is that in every triangle when you add the lengths of two sides, the resulting length should be greater than the length of the remaining sides. Let's say a, b, c are the sides of the triangle.
public static void main(String[] args){
int a=3, b=4, c=5;
if(a+b > c && a+c>b && c+b>a){
System.out.println("This is a valid trianlge");
}
else{
System.out.println("This is not a valid triangle");
}
}
make sure you replace the values of a,b, and c with the values you gain from user input.