Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

in JAVA why my code is not running Scanner k = new Scanner(System.in); System.ou

ID: 3739832 • Letter: I

Question

in JAVA

why my code is not running   

Scanner k = new Scanner(System.in);
System.out.println("Please enter a string: ");
String str = k.nextLine();
System.out.println("Please enter a character: ");
String input = k.nextLine();
char a = input.charAt(0);
int count = 0;

for(int i= 0;i<= str.length(); i++)
{
if(str.charAt(i) == a)
count ++;
}
if(count <= 0)
System.out.println("Character not found in the string ");
else
System.out.println("The number of character appears in the string is " + count);

Explanation / Answer

import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
System.out.println("Please enter a string: ");
String str = k.nextLine();
System.out.println("Please enter a character: ");
String input = k.nextLine();
char a = input.charAt(0);
int count = 0;

// index will be from 0 to the length-1
for(int i= 0;i< str.length(); i++)
{
if(str.charAt(i) == a)
count ++;
}
if(count <= 0)
System.out.println("Character not found in the string ");
else
System.out.println("The number of character appears in the string is " + count);
}
}

/*SAMPLE OUTPUT
Please enter a string:
cheggindia
Please enter a character:
i
The number of character appears in the string is 2
*/