Docsity

Java Programming: Finding the First Occurrence of a Character in a String, Lecture notes of Accounting

Toggle sidebar
bg1
BIO 340 Java
String inputString is read from input. If inputString does not contain character
'n' at or after index 2, then output "Character 'n' is not found at or after index 2."
Otherwise, output:
"Starting at index 2, the first occurrence of character 'n' is at index "
the index of the first occurrence of 'n' at or after index 2 in inputString
"."
End with a newline.
Ex: If the input is necklace, then the output is:
Character 'n' is not found at or after index 2.
Ex: If the input is application, then the output is:
Starting at index 2, the first occurrence of character 'n' is at index 10.
(
import java.util.Scanner;
public class FindCharacter {
( public static void main(String[] args) {
( ( (Scanner scnr = new Scanner(System.in);
( ( (String inputString;
( ( (int index;
( ( (
( ( (inputString = scnr.next();
pf3
pf4

Partial preview of the text

Download Java Programming: Finding the First Occurrence of a Character in a String and more Lecture notes Accounting in PDF only on Docsity!

BIO 340 Java String inputString is read from input. If inputString does not contain character 'n' at or after index 2, then output "Character 'n' is not found at or after index 2." Otherwise, output:  "Starting at index 2, the first occurrence of character 'n' is at index "  the index of the first occurrence of 'n' at or after index 2 in inputString  "." End with a newline. Ex: If the input is necklace, then the output is: Character 'n' is not found at or after index 2. Ex: If the input is application, then the output is: Starting at index 2, the first occurrence of character 'n' is at index 10. import java.util.Scanner; public class FindCharacter { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String inputString; int index; inputString = scnr.next();

/* Your code goes here */ } } You can use the indexOf() method of the String class in Java to find the first occurrence of a specific character in a string starting from a specific index. If the character is not found, indexOf() returns -1. Here is how you can implement this in your code: index = inputString.indexOf('n', 2 ); if (index == - 1 ) { System.out.println("Character 'n' is not found at or after index 2."); } else { System.out.println("Starting at index 2, the first occurrence of character 'n' is at index " + index + "."); } This code first tries to find the index of the first occurrence of 'n' in inputString starting from index 2. If 'n' is not found at or after index 2, indexOf() returns -1 and the first message is printed. If 'n' is found, the index of its first occurrence is printed in the second message.

This code will work as expected according to your problem statement.