Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
How to add two integers in one line

Hello im new to java and in my class my prof wants us to create a program that will compute the sum of two numbers. (Use methods) For example: Input an integer: 95 //Expected Output: The sum is 14 //(9+5=14)

im really lost on this one because i really don't know how to do this please help

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

From an algorithm point of view, the easiest way would be to:

  • convert the integer to a string
  • iterate the characters
  • convert each character back to an int
  • do the sum

In "Modern" java:

String.valueOf(test).chars().mapToLong(c -> Long.parseLong("" + (char) c)).reduce(Long::sum).getAsLong()

In older java:

int test = 95;
long sum = 0;
for (char c : String.valueOf(test).toCharArray()) {
    sum += Integer.parseInt(String.valueOf(c));
}
System.out.println(sum);

In javascript:

let sum = 0
for (let c of String(test)) {
    sum += parseInt(c)
}
console.log(sum)
about 4 years ago · Juan Pablo Isaza Report

0

If you use Java you can use this code:

int num = 95;
int sum = 0;

while (0 != num) {
    // add the last digit of the given number to the sum
    sum = sum + (num % 10);
    // remove the last digit of the given number
    num = num / 10;
}

System.out.println(sum);

(The code in JavaScript is very similar)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!