Task #4: Writing value returning Methods
In this task, you are being asked to write value returning methods in Java.
Write a method called charAtPosition() that accepts two arguments: a String object, and a
positive integer. It then returns the character located at position given by the integer argument.
You may use the following header for this method:
static char charAtPosition(String word, int position)
For example, if the method is called with the arguments, "GIFT University" and 5, the method
returns the character ‘U’ and a sample output should be:
Character at position 5 is: U
NOTE: A String starts from character position 0. Also, perform input validation so that the
position must be greater than or equal to 0.
HINT: Use the charAt(index) method of the String to find the character in a String.
1. Create a program called CharacterPositionLab1.java.
2. Correctly call the method with appropriate arguments.
3. Correctly display appropriate messages.
import java.util.Scanner;
public class CharacterPositionLab1{
static char charAtPosition(String word, int position){
return word.charAt(position);
}
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a word:");
String word = input.nextLine();
System.out.print("Enter a position: ");
int position = input.nextInt();
if(position>=0 && position<word.length()){
System.out.printf("Character at position %d is: %c\n\n",position,charAtPosition(word,position));
}else{
System.out.printf("Wrong position\n");
}
input.close();
}
}
Comments
Leave a comment