How do you create a loop that reads ints by their

2019-08-16 07:08发布

问题:

So I'm having trouble with this program, I have to have the user input a sequence of 0's and 1's. And then I have to use recursion to calculate the non-negative int and print it. This is the code I currently have, and it compiles.

import java.util.Scanner;

public class Bin {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.print("Please enter a sequence of 1's and 0's");
    String binInput = scan.next();
    System.out.println(binaryToDecimal(binInput));
  }

  public static int binaryToDecimal(String binString) {
    int size = binString.length();

    if (size == 1) {
        return Integer.parseInt(binString);
    } else {
        return binaryToDecimal(binString.substring(1, size)) + Integer.parseInt(binString.substring(0, 1)) * (int) Math.pow(2, size - 1);
    }

  }
  }

The problem is creating something that reads an int that the user input for example 11101 and read it number by number to check if there are any other numbers in there. If the user puts in a non-1 or 0 number it's supposed to print an error, which I have the code for. This is what I have:

for (int index = 0; index < n.length();
    index++) {
    char aChar = n.charAt(index);
    }

Now I know n.charAt(index) and n.length are wrong but I don't know how to write it to convert properly.

回答1:

Hint

You can not perform n.length() or n.charAt() (basically String operations) on an int. Change n to String.

So whenever you need n as Integer, use Integer.parseInt(n) and when you need n as String, use Integer.toString(n).