+ 1

help please! i want display what i written with a method

import java.util.Scanner; public class HelloWorld { public static Scanner sc =new Scanner(System.in); public static void main(String[] args) { String [] tab =new String[1]; int res=0, n=3; System.out.println("Hello world!"); do{ question(tab); res++; }while(res<n); afficher(tab); } public static void question(String[]tab){ String Q; for(int i=0;i<tab.length;i++){ System.out.println("Entrez une question :"); Q=sc.nextLine(); tab[i]=Q; } } public static void afficher(String []tab){ for(int i=0;i<tab.length;i++){ System.out.println(tab[i]); } } }

27th Dec 2017, 8:47 AM
TARCHID Bouabdellah
TARCHID Bouabdellah - avatar
2 Respostas
+ 2
The problem here is that you've created a String array with a single element and your loop will assign to the same string 3 times. It's a simple fix. 1. You'd have to change String[] tab = new String[1] to String[] tab = new String[3]; 2. Since the question() method already assigns the questions to your tab-array based on its length, the loop is unnecessary. You can simply call question(tab) directly from main. Alternatively, you can keep the do-while loop in your main method and change it to: do { tab[res] = getQuestion(); res++; } while (res < n); And have a method return the question as a String. public static String getQuestion() { String question; System.out.println("Entrez une question:"); question = sc.nextLine(); return question; } If you go with the 2nd approach, I would suggest assigning tab.length to 'n' in case you want to expand/shrink the array in the future and to eliminate errors/magic numbers.
2nd Jan 2018, 12:20 AM
Cluck'n'Coder
Cluck'n'Coder - avatar
+ 1
thanks for your answer it works fine. Happy New Year
2nd Jan 2018, 9:50 AM
TARCHID Bouabdellah
TARCHID Bouabdellah - avatar