In: Computer Science
Java Programming Create a class named Problem1, and create a main method, the program does the following:
- Prompt the user to enter a String named str. - Prompt the user to enter a character named ch.
- The program finds the index of the first occurrence of the character ch in str and print it in the format shown below.
- If the character ch is found in more than one index in the String str, the program prints the first index only.
- You may not use any built-in String methods to complete the task. You can only use the chartAt()and length() methods from the String class.
- Copy the output to a text file named Problem1.txt example output:
https://media.cheggcdn.com/media/c1a/c1a52903-6edb-4c01-a19d-dbb94d7a6308/phpvOMJmm.png
// Required program
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
public class Problem1
{
public static void main(String[] args) throws
IOException {
Scanner scanner = new Scanner(System.in);
//Instantiating the File class
File file = new File("Problem1.txt");
//Instantiating the PrintStream class
PrintStream stream = new PrintStream(file);
System.out.print("Enter a text: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to look for:
");
char ch = scanner.next().charAt(0);
boolean flag = false;
String outputString = "";
for(int i = 0; i < inputString.length(); i ++)
{
if(inputString.charAt(i) == ch){
outputString = ch + " was found at index " + i;
flag = true;
break;
}
}
if(flag == false) {
outputString = ch + " was not found in the String " +
inputString;
}
System.out.println(outputString);
System.out.println("Output copied to the text file " +
file.getAbsolutePath());
System.setOut(stream);
System.out.println("Enter a text: " + inputString);
System.out.println("Enter a character to look for: " + ch);
System.out.println(outputString);
}
}
// Outputs:
CONSOLE OUPUT
PROBLEM1.TXT FILE OUTPUT
CONSOLE OUTPUT
PROBLEM1.TXT FILE OUTPUT