Complete Question:
Write a method named showChar. The method should accept two arguments: a reference to a String object and an integer. The integer argument is a character position within the String, with the first character being at position 0. When the method executes, it should display the character at that character position. The method does not return anything.
Here is an example of a call to the method:
showChar("New York", 2);
In this call, the method will display the character w because it is in position
2. Demonstrate the method in a complete program.
Answer:
import java.util.Scanner;
public class ANot {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter a word");
String word = in.next();
System.out.println("Enter an index position, a positive number please");
int n = in.nextInt();
showChar(word,n);
}
public static void showChar(String word, int n){
System.out.println(word.charAt(n));
}
}
Step-by-step explanation:
- In creating the method showChar, we declared it to be void (since it will return no value) and to receive two parameters a string and an int
- Using the string method charAt in java, the method prints the character at index n
- We created a main method where a user is prompted to enter values for the string and the index
- The method showChar is then called and passed the values