I've been learning Java for one week now and I came across this solution for my homework, but I just can't understand how it calculates the sum of numbers.
I've tried to understand it for 1 hour now and I feel so dumb right now.
I pretty much understand that for add to x + 1 every time when the length of the entered number is lower than x which is 0. But I just can't get what the code inside for does.
sum += Integer.parseInt(String.valueOf(a.charAt(x)));
Here is the full code
public class Loader {
public static void main(String[] args) {
System.out.println(sum(8313));
}
public static Integer sum(Integer number){
String a = Integer.toString(number);
Integer sum = 0;
for(int x = 0; x < a.length(); x++) {
sum += Integer.parseInt(String.valueOf(a.charAt(x)));
}
return sum;
}
}
Actually, what you understood was wrong. (Or at least how you put it into words).
The for loop is used to loop through a range of numbers. In this case, it loops through 0 to a.length(), which is the number of digits in your number (The number variable). So in each iteration (or the step of the loop), the value of the x increases. It's not 0 all the time.
In each iteration, the for loop checks whether the x is still lesser than the number of digits in your number. If it reaches the limit, the loop exits.
Before entering the loop, you convert the number to a String. So, inside the loop, you first get the character at the index of the value of x. Basically, you take the character by character in your number. Then you convert it back to a digit using:
Integer.parseInt(String.valueOf(a.charAt(x)))
Then, it is added to the sum. This is pretty much the same as this:
for(int x = 0; x < a.length(); x++) {
char c = a.charAt(x);
String s = String.valueOf(c);
int digit = Integer.parseInt(s);
sum = sum + digit;
}
Your code just does all four steps in one line! When you come up with such cases, try to break down the code like this. That'll help you to understand it better.
Let's break down the line sum += Integer.parseInt(String.valueOf(a.charAt(x)));
First of all sum += 1 is the same as sum = sum + 1, so sum += Integer.parseInt(String.valueOf(a.charAt(x))); is equal to sum = sum + Integer.parseInt(String.valueOf(a.charAt(x)));
Integer.parseInt("1") transforms the String "1" into a number, so "1" => 1. Adding a variable of the type String to a number like sum += "1" would give an error
String.valueOf() on the other hand can transform a number or other datatype into a String, so 1 => "1". In this case it is used to transform a Character to the String datatype
a.charAt(x) takes the Character from the String a at the point x So if you have a = "Brentspine" then a.charAt(1) would return "r", since indexing starts at 0
So the line takes the character at position x from the String and makes it a string. Character is its own class so it has to be transformed into a String. Then this String is transformed into a number and added to the sum variable
The fori loop repeats itself the length of the String a times. For every time it run, the x variable gets increased by 1. This way it adds the number at the position x of the String a to the sum variable, which gets returned.
It basically says for the input "8315":
Repeat 4 times, increase x=0 by 1 every time.
Take the Character of the String at position a, make it an int and add it to sum
Related
This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.
System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
array[i] = console.nextInt();
}
for (i = 0; i < length -1; i++); {
if (array[i] % 2 != 0) {
count++;
}
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}
Example of console:
2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit
3
Enter length of sequence
4
Enter the sequence:
1
2
3
4
The count of odd integers in the sequence is 0
I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.
Remove the semi-colon (;) in the line
for (i = 0; i < length -1; i++);
the semi-colon terminates the loop hence an assumption that your line does nothing.
After the second for there is a semicolon that shouldn't be there. The syntax is technically correct however, there is nothing to execute so the block that checks for odd numbers is going to be executed only once. I suggest using a debugger that will help you troubleshoot issues easier.
I am tasked with creating a program in java which calculates the square root of a double and goes through each step of calculating it manually. The requirements are:
split the number into number pairs including the decimal point (1234.67 -> 12 34 67) to prepare for subtraction. If the number is uneven, a zero must populate (234.67 -> 02 34 67)
Print each pair (each pair is a minuend), one at a time, into the console and have the console show the subtraction. Subtrahend starts at 1 and so long as the result >= 0, the subtrahend increases by 2.
The count of subtrahends is the first number of the final square root output, the count of subtrahends from the second round is the second number of the square root output, etc.
From the first subtrahend round, take the remainder and join it to the second number pair, this is the new minuend for the second round of subtraction
Calculate the second subtrahend in round two by doubling the first number of the square root output and adding 1 in the first digit position
Repeat step 2, increasing by 2 each time
Step 5 and 6 repeat until two decimal places are reached
My question is with the number pairs in step 1 and getting the subsequent subtrahends after step 3 as a number to calculate. We are given the following visual:
My current thought is to put the double into a string and then tell java that each number pair is a number. I have a method created which creates a string from a double, but I am still missing how to incorporate the decimal place numbers. From my C class, I remember multiplying decimals by 100 to "store" the decimal numbers before converting them back later with another division by 100. I'm sure there is a java library that is able to do this but we are specifically not allowed to use them.
I think I should be able to continue on with the rest of the problem once I get past this point of splitting the number into number pairs inclusive of the decimals.
This is also my first stack post so if you have any tips on how to better write questions for future posts that would be helpful as well.
This is my current array method to store a given double into an array:
public static void printArray(int [] a) //printer helper method
{
for(int i = 0; i < a.length; i++)
{
System.out.print(a[i]);
}
}
public static void stringDigits (double n) //begin string method
{
int a [] = new int [15];
int i = 0;
int stringLength = 0;
while(n > 1)
{
a[i] = (int) (n % 10);
n = n / 10;
i++;
}
for(int j = 0; a[j] != 0; j++)
{
System.out.print(a[j]);
if(a[j] != 0)
{
stringLength++;
}
}
System.out.println("");
System.out.println(stringLength);
int[] numbersArray = new int[stringLength];
int g = 0;
for(int k = a.length-1; g < numbersArray.length; k--)
{
if(a[k] > 0)
{
numbersArray[g] = a[k];
g++;
}
}
System.out.println("");
printArray(numbersArray);
}
I've tried at first to store the value of the double into an int[] a array so that I can then select the numbers in pairs and then somehow combine them back into numbers. So if the array is {1,2,3,4,5,6} my next idea is to get java to convert a[0] + a[1] into the number 12 to prepare for the subtraction step.
This link looks close but does anyone know why the numbers are "10l" and "100l" etc? I've tested some of the answers and they dont produce the proper squareroot compared to the sqrt function from the math library.
Create a program that calculates the square root of a number without using Math.sqrt
This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 5 years ago.
I am trying to fetch second digit from a long variable.
long mi = 110000000;
int firstDigit = 0;
String numStr = Long.toString(mi);
for (int i = 0; i < numStr.length(); i++) {
System.out.println("" + i + " " + numStr.charAt(i));
firstDigit = numStr.charAt(1);
}
When I am printing firstDigit = numStr.charAt(1) on console. I am getting 1 which is expected but when the loop finishes firstDigit has 49.
Little confused why.
Because 49 is the ASCII value of char '1'.
So you should not assign a char to int directly.
And you don't need a loop here which keeps ovveriding the current value with charAt(1) anyway.
int number = numStr.charAt(1) - '0'; // substracting ASCII start value
The above statement internally works like 49 -48 and gives you 1.
If you feel like that is confusious, as others stated use Character.getNumericValue();
Or, although I don't like ""+ hack, below should work
int secondDigit = Integer.parseInt("" + String.valueOf(mi).charAt(1));
You got confused because 49 is ASCII value of integer 1. So you may parse character to integer then you can see integer value.
Integer.parseInt(String.valueOf(mi).charAt(1)):
You're probably looking for Character.getNumericValue(...) i.e.
firstDigit = Character.getNumericValue(numStr.charAt(1));
Otherwise, as the variable firstDigit is of type int that means you're assigning the ASCII representation of the character '1' which is 49 rather than the integer at the specified index.
Also, note that since you're interested in only a particular digit there is no need to put the statement firstDigit = numStr.charAt(1); inside the loop.
rather, just do the following outside the loop.
int number = Character.getNumericValue(numStr.charAt(1));
you only need define firstDigit as a char type variable, so will print as character.
since you define as int variable, it's value is the ASCII value of char '1': 49. this is why you get 49 instead of 1.
the answer Integer.parseInt(String.valueOf(mi).charAt(1)+""); is correct.
However, if we want to consider performace in our program, we need some improvements.
We have to time consuming methods, Integer.parseInt() and String.valueOf(). And always a custom methods is much faster than Integer.parseInt() and String.valueOf(). see simple benchmarks.
So, high performance solution can be like below:
int y=0;
while (mi>10)
{
y=(int) (mi%10);
mi=mi/10;
}
System.out.println("Answer is: " + y);
to test it:
long mi=4642345432634278834L;
int y=0;
long start = System.nanoTime();
//first solution
//y=Integer.parseInt(String.valueOf(mi).charAt(1)+"");
//seconf solution
while (mi>10)
{
y=(int) (mi%10);
mi=mi/10;
}
long finish = System.nanoTime();
long d = finish - start;
System.out.println("Answer is: " + y + " , Used time: " + d);
//about 821 to 1232 for while in 10 runs
//about 61225 to 76687 for parseInt in 10 runs
Doing string manipulation to work with numbers is almost always the wrong approach.
To get the second digit use the following;
int digitnum = 2;
int length = (int)Math.log10(mi));
int digit = (int)((mi/Math.pow(base,length-digitnum+1))%base);
If you want a different digit than the second change digitnum.
To avoid uncertainty with regards to floating point numbers you can use a integer math library like guavas IntMath
Let's take a look
System.out.println(numStr.charAt(1));
firstDigit = numStr.charAt(1);
System.out.println(firstDigit);
The result wouldn't be the same you will get
1
49
This happens because your firstDigit is int. Change it to char and you will get expected result
You can also do like below,
firstDigit = Integer.parseInt( numStr.charAt(1)+"");
So it will print second digit from long number.
Some things which have not been mentioned yet:
The second digit for integer datatypes is undefined if the long number is 0-9 (No, it is not zero. Integers do not have decimal places, this is only correct for floating-point numbers. Even then you must return undefined for NaN or an infinity value). In this case you should return a sentinel like e.g. -1 to indicate that there is no second digit.
Using log10 to get specific digits looks elegant, but they are 1. one of the numerically most expensive functions and 2. do often give incorrect results in edge cases. I will give some counterexamples later.
Performance could be improved further:
public static int getSecondDigit(long value) {
long tmp = value >= 0 ? value : -value;
if (tmp < 10) {
return -1;
}
long bigNumber = 1000000000000000000L;
boolean isBig = value >= bigNumber;
long decrement = isBig ? 100000000000000000L : 1;
long firstDigit = isBig ? bigNumber : 10;
int result = 0;
if (!isBig) {
long test = 100;
while (true) {
if (test > value) {
break;
}
decrement = firstDigit;
firstDigit = test;
test *= 10;
}
}
// Remove first
while (tmp >= firstDigit) {
tmp -= firstDigit;
}
// Count second
while (tmp >= decrement) {
tmp -= decrement;
result++;
}
return result;
}
Comparison:
1 000 000 random longs
String.valueOf()/Character.getNumericValue(): 106 ms
Log/Pow by Taemyr: 151 ms
Div10 by #Gholamali-Irani: 45 ms
Routine above: 30 ms
This is not the end, it can be even faster by lookup tables
decrementing 1/2/4/8, 10/20/40/80 and avoid the use of multiplication.
try this to get second char of your long
mi.toString().charAt(1);
How to get ASCII code
int ascii = 'A';
int ascii = 'a';
So if you assign a character to an integer, the integer will be holding the ASCII value of that character. Here I explicitly gave the values, in your code you are calling a method that returns a character, that's why you are getting ASCII instead of digit.
Help me to understand how this code works. It essentially adds commas into a string of numbers. So if the user types a 1 to 3 digit number it is unchanged. For a four digit number ,it adds a comma so
1111 becomes 1,111
11111 becomes 11,111
111111111 becomes 11,111,111
and so on. Here's the code:
private String addCommasToNumericString (String digits)
{
String result = "";
int len = digits.length();
int nDigits = 0;
for (int i = len - 1; i >= 0; i--)
{
result = digits.charAt(i) + result;
nDigits++;
if (((nDigits % 3) == 0) && (i > 0))
{
result = "," + result;
}
}
return (result);
}
I´ll explain what I do understand of it
The for loop basically counts the length of the number the user has written to avoid putting a comma before the first number (e.g. ,1111). And while i is less than the length of the string it subtracts 1.
result returns the char at position i, since it counts downwards it returns the chars "opposite" from right towards left.
nDigits adds 1 from to the initial value of 0 on each iteration through the loop.
I guess now is where I am having trouble seeing exactly what is going on: if ("nDigits % 3) == 0.
So for the two first iteration through loop it will not execute the if loop because:
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
nDigits starts out as 1 because of the nDigits++ code inside the for loop, so how does it put the comma after three digits and not two? And how does it know when there is only 4 or 5 digits to place the comma corretly at position 1 and two (1,111 - 11,111)?
I think the easiest way to explain this is to slow it down to each pass.
The loop starts at the end of the string so if you have the string 12345, then after the first time through the loop result will be "5" and nDigits will be 1.
The next time through, '4' will be added to the front of the result giving you "45" and nDigits will be 2.
The third time through, it adds '3' to the front of result making that "345" and then the if-then triggers and adds a comma to the front. Result is now ",345".
More passes will give you "12,345".
I think what is confusing you is that loop starts at the '5' and not at the '1'. Everything is added to the front of result and not to the end as you would normally expect.
Hope this helps!
The key thing in this method is to count the digits from right to left. If you don't do it that way it won't work.
You can also do the same with String Manipulation instead of char manipulation. Maybe it makes it easier to understand so I'll provide an example.
My solution involves the use of the subString Method and operates in a similar manner to yours. Starting FROM RIGHT TO LEFT, it divides the original String in two substrings and adds a comma in between them every time there is a 3 digits group.
private String addCommas (String digits) {
String result = digits;
if (digits.length() <= 3) return digits; // If the original value has 3 digits or less it returns that value
for (int i = 0; i < (digits.length() – 1) / 3; i++) {
int commaPos = digits.length() – 3 – (3 * i); // comma position in each cicle
result = result.substring(0, commaPos) + "," + result.substring(commaPos);
}
return result;
}
The variable result is used for incremental build of the final output, in each iteration one or two chars are concatenated from left (i.e. the string is build from right to left).
One char is concatenated everytime by running
result = digits.charAt(i) + result;
it is the actual digit
the second char is concatenated in each third iteration by running
result = "," + result;
it is the order separator
The implementation is not optimal at all, because in Java the string are immutable and result = "," + result; ends up in creating a new object. The StringBuffer or StringBuilder are far more effective for this purpose.
Essentially what this does is start at the last digit of the number and iterate through from right to left, prepending them to the result String and putting a comma in every 3 characters.
In this particular code, len holds the total length of the number and nDigits is a count of how many of those digits have been evaluated already. Starting at position len-1 (so the index of the last digit of the number), the for-loop iterates through position 0 (the first digit of the number). It takes the digit at position i, puts it at the front of the result String, and then evaluates if there should be a comma in front of it. nDigits % 3 will return 0 every 3rd digit, so the if statement evaluates if there should be a comma by checking that if there have been 3 digits written and the one you just wrote was not 0.
for (int i = len - 1; i >= 0; i--)
i starts with len - 1, to start from the last digit. i > 0 in if (((nDigits % 3) == 0) && (i > 0)) is the one that avoid a comma before the first number (e.g. ,1111).
I modified answer of #Antonio Ricardo Diegues Silva for my purposes.
/**
* Get number in {#link String} with divider after 'n' number of digits
* #param number number for processing
* #param n amount after which will be inserted divider
* #return {#link String} number with dividers
*/
public static <T extends Number> String insertDividerBetweenEveryNDigits(T number, int n, String divider) {
StringBuilder builder = new StringBuilder().append(number);
int digitsNumber = builder.length();
if (digitsNumber > n) { // If the original value has n digits or less it just returns that value
for (int i = 1; i <= (digitsNumber - 1) / n; i++) {
int dividerPos = digitsNumber - (n * i); // divider position in each cycle
builder.insert(dividerPos, divider);
}
}
return builder.toString();
}
/*
* Application the reads an integer and prints sum of all even integers between two and input value
*/
import java.util.Scanner;
public class evenNumbers{
public static void main(String [] args){
int number;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer greater than 1:");
number = scan.nextInt();
printNumber(number);
}// end main
/*declares an int variable called number and displays it on the screen*/
public static void printNumber(int number){
if (number < 2){
System.out.println("Input value must not be less than 2");
}
int sum = 2;
if(number % 2==0){
sum+= number;
}
System.out.println("Sum of even numbers between 2 and " + number + " inclusive is: " + sum);
}//end printnumber
}
I need to calculate the sum of 2 to the input number inclusive however, it only takes the last number and add two to it. COuld someone help me fix this.
You need a loop. Your comment hints at the right direction, but you should look at the Java tutorials to see how to correctly write a 'for' loop. There are three parts: the initial declaration, the terminating condition and the loop step. Remember that the ++ operator only adds one to the variable. You can add other values using +=. If you use += to add a different value (like 2) to the loop variable, you can skip the 'if' test for even numbers. You can test for boundaries inclusively using the <= and >= comparison operators (for primitives). So you want something like this (in pseudocode, not Java):
input the test value
Optional: reject invalid test value and **exit with message if it is not valid!**
initialize the sum variable to zero
for ( intialize loop variable to 2; test that loop var <= test value; add 2 to loop var )
{
add 'number' to the sum variable
}
display the sum
int sum = 0;
for (int current = 2; current <= number; current += 2)
sum += current;