0

I want to scan a String and its content. I want to return an error message if there are any character in the string. For example: int a = myFunction("123"); will save "123" in a, but when the user tries to do something like int a = myFunction("12s32"); it should return the error, because there is a character in the string. This is what i got so far:

public class Parseint {
    public static int parseInt(String str) {
        if (str == null || str.isEmpty()) {
            System.out.println("Der String enthaelt keine Zeichen");
            return -1;
        } else {
            int sum = 0;
            int position = 1;
            for (int i = str.length() - 1; i >= 0; i--) {
                int number = str.charAt(i) - '0';
                sum += number * position;
                position = position * 10;
            }
            return sum;
        }
    }

    public static void main(String[] args) {
        int a = parseInt("");
        System.out.println(a);
    }
}
ArK
  • 20,698
  • 67
  • 109
  • 136
ethanqt
  • 63
  • 5
  • So you want to exclude letters - you may want to exclude non-digits. (You may want to use a tag or otherwise mention a specific programming language.) You know how to use a conditional statement: `if () { return ;` (no need to use an `else` after this (early out): decreases nesting depth/indentation). You know how to denote a `char` literal and perform arithmetic with it: `str.charAt(i) - '0'`. You can do comparisons, too. – greybeard Dec 10 '16 at 09:01
  • Thank you for your reply! My way of thinking is to create a for-loop which searchs for "invalid" input. In my case everything except numbers. So im stuck in this situation and I dont know how to implement this. Should I do a comparison for every banned letter? Or should I only execute my function when the argument contains only numbers and nothing else? – ethanqt Dec 10 '16 at 12:18
  • You should _document, in the code, what it is supposed to accomplish_. You should assume that most time is spent on valid input: just try to proceed with useful processing and when you can't, give a meaningful indication of _why_. – greybeard Dec 10 '16 at 20:00

1 Answers1

0

Doing a try and catch like in this link suggests would work perfectly

A simple try and catch

SunnyH
  • 67
  • 11