Question: Write a Java program A2p1.java with a public class A2p1 and no named packages that takes one command line argument assumed to be a positive

Write a Java program A2p1.java with a public class A2p1 and no named packages that takes one command line argument assumed to be a positive integer n. The program should prompt the user to input n strings from stdin (one per line) and store all of them in an array. After the program reads in the input strings, it should print the longest input strings. Note that if there are more than one longest string they should all be printed. Two sample runs can look like the following (blue color means those are typed by the user):

[kwang@computer][~/temp]$ java A2p1 4

(User Input)2xx

8abc

5xyz

12

(output)The longest input strings are:

8abc

5xyz

[kwang@computer][~/temp]$ java A2p1 3

(User Input)a2

b3c

7

(Output)The longest input strings are:

b3c

My code :

import java.util.Scanner;

public class A2p1 {

public static void main(String[] args)

{

int n=Integer.parseInt(args[0]);//access the first command line argument

Scanner sc=new Scanner(System.in);

String[] inputStrings = new String[n];

int maxLength = 0;

System.out.println("Enter " + n + " strings: ");

for (int i = 0; i < n; i++) {

inputStrings[i] = sc.nextLine();

maxLength = Math.max(maxLength, inputStrings[i].length());

}

// Print the longest input strings

System.out.println("The longest input strings are: ");

for (int i = 0; i < n; i++) {

if (inputStrings[i].length() == maxLength) {

System.out.println(inputStrings[i]);

}}

}

}

Why does the console say

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at A2p1.main(A2p1.java:7)"

How would I rewrite and fix this issue so I can test my code to test and see if I can interest strings and tell which string is the longest.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!