Problème d'affichage de résultat

Bonjour,

Je ne sais pas pourquoi mon programme n'affiche pas les chiffres parmi une chaine de caractère pour les mettre dans un tableau d'entiers. Le voici.

import java.util.Scanner;
public class TD5_ex1 {

	public static void main(String[] args) {
		String ch ;
		
		Scanner s = new Scanner(System.in);
		System.out.println("Entrer la chaine: ");
		ch=s.nextLine();
		int i =0, j=0;
		int []tab= new int[ch.length()] ;
		while (i<ch.length()-1 && j<tab.length) {
			tab[j]=(int)(ch.charAt(i));
		}
		System.out.println(tab[j]);
		
		


Merci.

2 réponses

  1. Modérateur
    Bonjour,

    Ta boucle tourne en rond, tu n'incrémentes jamais ni i, ni j, donc le programme n'arrive jamais jusqu'à l'affichage.

    Remarque : tu n'as pas besoin de passer des caractères dans un tableau d'entier pour les convertir, tu peux les afficher tels quels...

    while (i < ch.length()) {
        System.out.println((int) (ch.charAt(i)));
        i++;
    }
    1. On me demande de les afficher dans un tableau d'entier donc je fais:

      	int i =0;
      		int []tab= new int[ch.length()] ;
      		while (i<ch.length() && i<tab.length) {
      			tab[i]=(int)(ch.charAt(i));
      			System.out.print(tab[i]);
      			i++;
      			
      		}
      

      Merci ça ne marche pas.
    2. Modérateur
      @ArmandAs_1998J'ai fait un copier-coller de ton code et ça fonctionne... quel est ton problème ?
  2. Moi, lorsque je fais entrer la chaine: 123, ça me donne: 4950.
    1. Modérateur
      Avec ton code et ta modif je tapes 123 et ça me donne bien 495051.
      (Je n'ai rien changé à part les deux accolades qui manquaient à la fin...)
      import java.util.Scanner;
      public class TD5_ex1 {
      
      	public static void main(String[] args) {
      		String ch ;
      		
      		Scanner s = new Scanner(System.in);
      		System.out.println("Entrer la chaine: ");
      		ch=s.nextLine();
      /*
      		int i =0, j=0;
      		int []tab= new int[ch.length()] ;
      		while (i<ch.length()-1 && j<tab.length) {
      			tab[j]=(int)(ch.charAt(i));
      		}
      		System.out.println(tab[j]);
      */
      	int i =0;
      		int []tab= new int[ch.length()] ;
      		while (i<ch.length() && i<tab.length) {
      			tab[i]=(int)(ch.charAt(i));
      			System.out.print(tab[i]);
      			i++;
      			
      		}
          }
      }

      Remarque :
      && i<tab.length
      est inutile.
      Vu que l'on a
      tab.length == ch.length()
      alors
      i<ch.length()
      suffit.