Instructions:
Create a variable that accepts a positive integer.
Create an empty list. Then, using loops, add string values to your list using the input() function. The number of string values to be added are dependent on the inputted value on the first inputted integer.
Create another variable that accepts a non-negative integer. The number must only range from 0 until the value of the first inputted integer.
Using your understanding on accessing list elements, access and print out the list element having the index position of the second inputted integer.
Input
The first line contains an integer n which is the size of the array.
The next n lines contains a string on each.
The last line contains an integer which is the index to be accessed and printed.
6
Learning
Programming
made
easy
with
Cody!
5
Output
A line containing a string.
Cody!
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int n=in.nextInt();
String [] str=new String[n];
System.out.println("Enter "+n+" strings: ");
for(int i=0;i<n;i++){
str[i]=in.next();
}
int x;
System.out.print("Enter the index to be accessed and printed: ");
x=in.nextInt();
System.out.println(str[x]);
}
}
Comments
Leave a comment