Lab 2.2.1 Construct a program that uses a single dimension array called names to
ID: 3860153 • Letter: L
Question
Lab 2.2.1
Construct a program that uses a single dimension array called names to store the names: bill, milo, and opus.
Create an output statement the prints out the name "opus" from the array.
Create an output statement that prints out all the names in the array
Construct another single dimension array called numbers that stores the values: 12, 30, 100, 103.5
Create an output statement that prints out all the elements in the array
Lab 2.2.2
Construct a program that will ask the use to input the names of four (4) people. The four names will be stored in an array called names.
The program will then print out the names of the first 2 people only.
Explanation / Answer
Lab 2.2.1
ArrayTest.java
public class ArrayTest {
public static void main(String[] args) {
String names[] = {"bill", "milo", "opus"};
System.out.println(names[2]);
System.out.println(names[0]+" "+names[1]+" "+names[2]);
double numbers[] = {12, 30, 100, 103.5};
System.out.println(numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]);
}
}
Output:
opus
bill milo opus
12.0 30.0 100.0 103.5
Lab 2.2.2
NamesArray.java
import java.util.Scanner;
public class NamesArray {
public static void main(String[] args) {
String names[] = new String[4];
Scanner scan = new Scanner(System.in);
for(int i=0;i<names.length;i++){
System.out.print("Enter the name: ");
names[i]=scan.nextLine();
}
System.out.println(names[0]+" "+names[1]);
}
}
Output:
Enter the name: Suresh
Enter the name: Sekhar
Enter the name: Anshu
Enter the name: Revathi
Suresh Sekhar
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.