Can someone please explain how my code continues to get a wrong answer? It’s like CodeChefe wants their answer, and doesn’t care if it is correct or not.
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int temp, n , sum = 0;
temp = in.nextInt();
while (temp > 0) {
n = temp % 10;
sum = sum + n;
temp /= 10;
}
System.out.println(sum);
}
}
Input
87
Output
15
If you mean this Problem, then don’t ask the user; just read in the number of testcases - the Input section tells you the exact format that the test input takes.
The Example Input gives you some nice test input (and the corresponding expected output): for the input
3
12345
31203
2123
your program should output precisely the following:
15
9
8
In general, I’d advise making sure that your program gives he right output for the Example Input before you submit - you can use the “Run” and the “Custom Input” features of the Codechef IDE to help you check this
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int t=in.nextInt();
while(t-- > 0){
int temp, n , sum = 0;
temp = in.nextInt();
while (temp > 0) {
n = temp % 10;
sum = sum + n;
temp /= 10;
}
System.out.println(sum);
}
}
}
According to my limited knowledge of java, This should work.
everule1, thanks for the help and inspiration! I was able to get it to work with the following:
import java.util.Scanner;
public class sumOfDigits {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a test number: ");
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int temp, n, sum = 0;
System.out.println("please enter a number: ");
temp = in.nextInt();
while (temp > 0) {
n = temp % 10;
sum = sum + n;
temp /= 10;
}
System.out.println(sum);
}
in.close();
}
}
I learned that if you declare the int temp, n, sum = 0; outside of the first loop, then it sums up each number.
Will add 15 + 9 + 8
public class sumOfDigits {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a test number: ");
int t = in.nextInt();
int temp, n, sum = 0;
for (int i = 0; i < t; i++) {
System.out.println("please enter a number: ");
temp = in.nextInt();
while (temp > 0) {
n = temp % 10;
sum = sum + n;
temp /= 10;
}
System.out.println(sum);
}
in.close();
}
}