How do I convert int to String and still count?

Viewed 79

So this is my code right know. The code works with putting in 123 and I get 6 as answer. But if I put 1 2 3 I get 1 as answer. I want the code to convert into a string, but if I putt a space I will give a error message but don't know how to do it. I have try different things but getting errors every time, so can someone help me out? I still want the code to count the sum of 123 but give a error message, "try again, with no space" if I put 1 2 3 in.

int m, n, sum = 0;
System.out.println("Skriv in de tal som du vill addera");
m = sc.nextInt();
    
while (m > 0) {
    n = m % 10;
    sum = sum + n;
    m = m / 10;
}

System.out.println("Summan av talen:" + sum);
}
3 Answers

If you want to get an error message when an input has spaces, try this piece of code:

String m;
int n, sum = 0;
        System.out.println("Skriv in de tal som du vill addera: ");
        try {
        m = sc.nextLine();
        int mm=Integer.parseInt(m);
        while (mm > 0) {
            n = mm % 10;
            sum = sum + n;
            mm = mm / 10;
            
        }
        System.out.println("Summan av talne: "+sum);
        }catch (Exception e) {
            System.out.println("try again, with no spaces.");
        }
    

This should catch the exception like you want when a string cannot be converted to int.

You'll need to read the input as a String (using the nextLine() method of Scanner), not as an integer, and store it in a variable of type String. Then, you can replace() the spaces with an empty string, and cast or convert it to int (parseInt(); should work), show the message and proceed like you are doing now.

Use Scanner#nextLine to scan the input as a String. If the input string contains space, split the input string and process each integer string in it; otherwise, parse the input string into an int using Ineteger#parseInt and then process it in the way you are already doing.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int m, n, sum = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Skriv in de tal som du vill addera: ");
        String input = sc.nextLine();

        if (input.contains(" ")) {
            // Split the input on optional space
            String[] nums = input.split("\\s+");

            // Process each integer string from the input
            for (String num : nums) {
                sum += Integer.parseInt(num);
            }
        } else {
            m = Integer.parseInt(input);

            while (m > 0) {
                n = m % 10;
                sum = sum + n;
                m = m / 10;
            }
        }
        System.out.println("Summan av talen: " + sum);
    }
}

A sample run:

Skriv in de tal som du vill addera: 123
Summan av talen: 6

Another sample run:

Skriv in de tal som du vill addera: 1 2 3
Summan av talen: 6
Related