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.
Related
public class Main
{
public static void main(String[] args)
{
int[] num = {1,2,3,4};
System.out.println(Counter.add(num));
}
}
Class
public class Counter
{
public static int add(int[] numb)
{
for(int i=0;i<numb.length;i++){
numb[i]++;
System.out.println(numb[i]);
int result = result + numb[i];
}
return result;
}
}
I am trying to output the total number in the array list, but with a twist, having +1 to each number in the array list, so 1,2,3,4 would give me 14, as 1+2+3+4 = 10 + 4 (+1 to each number), do I have to use .split to give me the total amount of variable in the array to add onto the total addition?
Do I have to use .split to give me the total amount of variable in the array to add onto the total addition?
No. You can simply return the sum, plus the length of the Array. Also you declare result within the for loop, so it is only in scope within the loop. Move it outside of the loop
public static int add(int[] numb)
{
int result = 0;
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]);
result += numb[i];
}
return result + numb.length;
}
Which, when called with the Array int[] num = {1,2,3,4}; outputs 14.
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'm trying to write a method (specifically using recursion) that would return the number of even digits in a natural number. I'd like to do so with a return type of NaturalNumber in order to gain more familiarity with it. Can someone point me in the right direction?
//private static NaturalNumber countEvenDigits(NaturalNumber num)
//initalize a NaturalNumber--count--to zero
//while loop with condition that the num is not 0
//initialize a NaturalNumber--k--to num.divideBy10 so that it is equal to the last digit in the natural number
//if statement-- k mod 2 is equal to 0
//increment the NaturalNumber count
//end if statement
//call this function recursively
//end while statement
//return count
However my current implementation just returns 0, what am I thinking about in a wrong way?
First if all, you posted this in Java, so I guess natural number is Integer (or int primitive)
Then your function needs to have a check in the beginning if the function call "end requirement" is fulfilled (number != 0).
If your number is != 0, you actually do the check if it is even or odd. After this check, you need to remember that (count++) and add the return value of the recursive method call onto your count, but with the last digit removed, because you checked that in this call already. (count += countEvenDigits(naturalNumber/10)). This should call itself as long as there are more digits and finally, it will get into the initial if() that exits.
/** http://stackoverflow.com/q/36085564/6077352 */
public class NaturalNumber {
public static void main(String[] args) {
int naturalNumber = 123456789;
System.out.println(countEvenDigits(naturalNumber));
}
private static int countEvenDigits(int naturalNumber) {
int count = 0;
if (naturalNumber != 0) {
if (naturalNumber % 2 == 0) {
count = count + 1;
}
count = count + countEvenDigits(naturalNumber / 10);
}
return count;
} }
Example output:
4
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.
I have an assignment introducing Recursion in Java and I am running into a roadblock. The assignment requires a recursion method to output a number of lines of a number of asterisks depending on the integer value passed to it. For example, if 4 is passed in as variable n, the output would have a first line of one asterisk, next line 2 asterisks, next 3 asterisks, next 4, then 4, 3, 2, & 1 going down.
I have been able to complete the first half of the output (not sure if it is optimal though), but have no clue how to get the method to reverse back down. This is all to be done in one method call with a variable (n) passed to the method.
Here is the method I have so far:
public static void myMethod(int n)
{
if (n <= 1) {
System.out.print("*");
} else {
myMethod(n - 1);
for (int i = 0; i < n; i++) {
System.out.print("*");
}
}
System.out.print("\n"); // new line
}
It is called from main with this:
myMethod(n);
So what I have is a for loop that will print an asterisk on the same line 'n' times. After the for loop it proceeds to the next line and cycles, changing n. But I have no idea how to get it to reverse.
My method prints from the method. My instructor showed me a sample version passing 2 variables (n) and a null string.
public static String myMethod(int n, String displayStr) {
String currentStr = "";
for (int i = 0; i < n; i++)
currentStr += "*";
currentStr += "\n";
if (displayStr == null){
return myMethod((n - 1), currentStr);
} // end base case
else if (n > 0){
return myMethod((n - 1), (currentStr + displayStr + currentStr));
}
else {
return displayStr;
}
} // end recursion method myMethod
His version prints from main using the following code line:
System.out.println(myMethod(n, null));
I have tried his version and it prints the triangle on it's side but the largest line only prints once instead of twice. I have spent all day trying to alter his to add in a duplicate line in the middle and am starting to think it isn't possible.
Any help would be GREATLY appreciated. I am at a complete standstill with this.
Change the method signature to public static void myMethod(int n, boolean reversed) where reversed is initialized to false but flips to true when you print n asterisks. Inside the method, reverse your logic if reversed is true.
You basically just need to print out the current row, then do the recursive call, then print the row again. That way, you get the stack buildup on the way up, and then again on the way down.
Here is an example that uses 2 parameters, one being the max length and the other being the iterator for the recursion.
// bootstrap method to start the recursion
public static void myMethod(int length)
{
myMethod(length, length);
}
public static void myMethod(int length, int i)
{
if (i > 0)
{
int rowLength = length - i + 1;
printRow(rowLength, '*');
myMethod(length, i - 1);
printRow(rowLength, '*');
}
}
public static void printRow(int length, char symbol)
{
for (int i = 0; i < length; i++)
System.out.print(symbol);
System.out.println();
}
Because the output counts up (not *down to zero), you must pass in the number of asterisks to print and the maximum number, so the terminating condition can be established.
Further, the pseudo code for your method is:
if n > max return (terminating condition)
print n asterisks
recursively call with n + 1
print n asterisks
A great deal of code simplification can be achieved if you pass in not the current length to print, but the String of asterisks, so your (private) recursive method could be simply:
private static void myMethod(int n, String s) {
if (s.length() < n) return;
System.out.println(s);
myMethod(n, s + "*");
System.out.println(s);
}
And your public method, which sets up the initial conditions, is then:
public static void myMethod(int n) {
myMethod(n, "*");
}
IMHO an elegant implementation with good code density.