First, launch NetBeans and close any previous projects that may be open (at the top menu go to File ==> Close All Projects).

Then, create a new Java application called "StringLength" (without the quotation marks) that requests a String from the user at the command line and finds its length. Your program should output: "Your string has a length of X characters." where X is the String's length. Allow for the String to be one or more words of input. Be sure to use the suitable method for determining the length of the String.

I have the below code but it is only giving me the output that "Your string has a length of x characters". it is not outputting that Hello, my name is John Smith.

package stringlength;

import java.util.Scanner;

public class StringLength
{

public static void main(String[] args) {
if(args.length > -1) {


String input = args[0];



int length = input.length(); // using length() method in String class
System.out.println("Your string has a length of "+length+" characters.");


System.out.println("Your string has a length of "+length+" characters.");
}
}
}

Respuesta :

Answer:

// name of the package

package stringlength;

// Scanner is imported but it is not needed

// So it is commented

// import java.util.Scanner;

// The class name StringLength is defined

public class StringLength {

// main method to signify the beginning of program execution

public static void main(String[] args) {

// if-statement to check if argument is supplied to

// command line

if(args.length > -1) {

// the first argument is read and assigned to input

String input = args[0];

int length = input.length(); // using length() method in String class

System.out.println("Your string has a length of "+length+" characters.");

} else {

System.out.println("Please enter your string argument in quote");

}

}

}

Explanation:

The code works fine with little modification and comments. The user should supply the string arguments in quote. The quote must surround the strings because our logic read the first argument passed to the command line. Inserting a string with space between them will provide a wrong output.

A sample image is attached.

Ver imagen ibnahmadbello
ACCESS MORE