Code does not work and returns no error (Java)

Asked

Viewed 129 times

0

I’m new to Java, and I can’t run this code:

package exercicio.pkg4;

import java.util.Scanner;

public class Exercicio4 {

    public static void main(String[] args) {

        Scanner ler = new Scanner(System.in);
        int x[] = new int[10];
        int i;
        int resto;

        for(i=1; i<=10; i++)
        {
            System.out.printf("Digite o %iº número\n",i);
            x[i] = ler.nextInt();
        }
        for(i=1; i<=10; i++)
        {
            resto = x[i]%2;
            if(resto == 0)
            {
                System.out.printf("%i <- numero par. ",x[i]);
            }else{
                System.out.printf("%i <- numero impar. ",x[i]);
            }
        }
    }

}

The following messages appear in the output:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'
    at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2691)
    at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2720)
    at java.util.Formatter.parse(Formatter.java:2560)
    at java.util.Formatter.format(Formatter.java:2501)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at exercicio.pkg4.Exercicio4.main(Exercicio4.java:16)
Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo)
  • Change %iº for %dº, resolves?

2 answers

2


Your code has two problems:

  • First of all there is no %i in the Printf, for values of the type int or Integer use %d and that’s what’s causing UnknownFormatConversionException described in your question;
  • Java arrays start at 0 which means that the first Indice is 0 and the last Indice is the tamnaho of the array - 1, if you look at your code you enter the first value at position 1 since the control variable i starts with 1 and goes up to 11 since it uses i <= 10, if not fixed your code will fire a ArrayIndexOutOfBoundsException.

Soon, your code with the fixes would be:

package exercicio.pkg4;

import java.util.Scanner;

public class Exercicio4 {

    public static void main(String[] args) {

        Scanner ler = new Scanner(System.in);
        int x[] = new int[10];
        int i;
        int resto;

        for (i = 0; i < 10; i++) {
            System.out.printf("Digite o %dº número\n", i + 1);
            x[i] = ler.nextInt();
        }

        for (i = 0; i < 10; i++) {
            resto = x[i] % 2;

            if (resto == 0) {
                System.out.printf("%d <- numero par. ", x[i]);
            } else {
                System.out.printf("%d <- numero impar. ", x[i]);
            }
        }

    }

}

-1

Good evening, use %d to decimal no %i

  • 3

    Bruno, try to explain the reason and give examples in your answers whenever possible. If not it can be considered of low quality.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.