Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign variables on a while loop in Java

I am doing a program where a user will input 8 names then I have to print it on a later part of the program. I can’t seem to do this. I am thinking of putting an array to assign them if that makes sense? I am doing this for 4 hours already lol. Here’s my code so far for this part.

    private static void testing() {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter Examples: ");
        int i = 0;
        while (i < 8) {
            String Examples = sc.nextLine();
                    i++;
        }

//then the part where the user inputs will be printed.

            }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

simply to declare a String array in java, you type:

String[] Examples = new String[8];

where 8 is the size of the array and then in the loop you can refer to which index of the array to store the input to, so for example this line:

Examples[i] = sc.nextLine();

will store the values in the String array.

to print the array, either write:

for (int j = 0; j < 8; j++) {
    System.out.println(Examples[j]);
}

or

for (String s : Examples)
    System.out.println(s);

and this is the full code edited:

import java.util.Scanner;
import java.util.regex.Pattern;

public class Main
{

    public static void main(String[] args) {
        testing();

    }
    private static void testing() {
        String[] Examples = new String[8];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter Examples: ");
        int i = 0;
        while (i < 8) {
            Examples[i] = sc.nextLine();
            i++;
        }

        for (String s : Examples)
            System.out.println(s);

    }

}

and this is some example input:

test1
test2
test3
test4
test5
test6
test7
test8
test1
test2
test3
test4
test5
test6
test7
test8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading