2

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);
}
  • Why not just delete spaces before cast to int ? https://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java – Alexy Aug 28 '20 at 09:46
  • @Alexy I have to use the scanner, or what do you mean before cast to int? If I write with space I want a error message to come out and say "try again, no space" – Mikaela Wallenius Aug 28 '20 at 09:53
  • You want to get an error message when there is spaces? Can you please specify? – Ralph Aouad Aug 28 '20 at 09:53
  • @MikaelaWallenius Ok I see, so you have to check if there is spaces. To do that, check your string with this : your_input.contains(" "), it will return true if there is at least one space. – Alexy Aug 28 '20 at 09:59

3 Answers3

3

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.

Ralph Aouad
  • 414
  • 4
  • 10
2

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.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24
  • But I don't know how to convert int to a string... that's my question – Mikaela Wallenius Aug 28 '20 at 09:48
  • `parseInt(String s);`, as per the [documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html) that you should have always at hand for reading when you don't know how to do a thing. It's very detailed and will tell you how to do most things. I'll add that to my answer – JustAnotherDeveloper Aug 28 '20 at 09:51
  • `String input = sc.nextLine()` will read the input (as a String) until the user hits *enter*. That will give you `"1 2 3"` as it is. Then as @JustAnotherDeveloper just proposed you could analyse your String. `input.contains(" ")` will test if the user added a whitespace somewhere, or `Integer.parseInt(input)` will throw an `NumberFormatException` when `"1 2 3"` is not a number (which it isn't, it's 3 numbers in a string).. – GameDroids Aug 28 '20 at 10:00
  • Ah, yes. OP said "convert int to string", not the opposite. My mistake. GameDroids' comment is correct. I'll clarify my answer. Thanks for catching that GameDroids. – JustAnotherDeveloper Aug 28 '20 at 10:03
1

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110