Inteiros em uma String

3 respostas
intstring
F

Como eu sei que uma String só possui números inteiro?

...
if(string.charAt(i) != int) {  //isso esta errado, qro saber como eu faço pra fazer 'diferente deInt             
     boolean tof = false;
}

3 Respostas

lvbarbosa
public static void main(String[] args) {
    String inteiros = "1 2 3 4 1 2 3 10 2138";
    String naoInteiros = "1 2 3 1 12350 2.5 203400 3";
    System.out.println(inteiros + " soh tem inteiros? " + sohInteiros(inteiros));
    System.out.println(naoInteiros + " soh tem inteiros? " + sohInteiros(naoInteiros));
}

public static boolean sohInteiros(String subject) {
    Scanner scanner = new Scanner(subject);
    while(scanner.hasNextInt()) {
        scanner.nextInt();
    }
    return !scanner.hasNext();
}

Outra forma mais ninja:

public static boolean sohInteiros(String subject) {
    return IntStream.range(0, subject.length()).noneMatch(i -> !ehNumeroOuEspaco(subject.charAt(i)));
}
public static boolean ehNumeroOuEspaco(char c) {
    return (c >= 48 && c <= 57) || (c == 32);
}

Mais uma:

public static boolean sohInteiros(String subject) {
    return subject.matches("(\\d+|\\s+)*");
}
D
char zero = '0';
char nove = '9';

if(string.charAt(i) < zero || string.charAt(i) > nove) {
  boolean tof = false;
}
staroski
if ( meuObjetoString.matches( "[0-9]+" ) ) {
    System.out.println("String só contém inteiros!");
}
Criado 9 de fevereiro de 2017
Ultima resposta 10 de fev. de 2017
Respostas 3
Participantes 4