Reputation: 45
this is the code i made, can someone explain me why the output stays 0.0?
(I was trying to make a program that converts binary to decimal, and i know that this can be easily accomplished in java in other ways)
package main;
import java.util.Scanner;
public class Class1 {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int length = input.length();
double output=0.0;
String reverse = new StringBuffer(input).reverse().toString();
for (int i=0; i==length; i+=1){
switch(reverse.charAt(i)){
case '1': output = (output + (Math.pow(2, i)));break;
case '0': break;
}
}
System.out.println(output);
}
}
Upvotes: 1
Views: 290
Reputation: 140514
Unless length == 0
, that for loop never executes.
You might well mean something like:
for (int i=0; i<length; i+=1){
Also, there is no need to use Math.pow(2, i)
- you can use 1 << i
and keep it all as an integer.
Upvotes: 4