Java code works fine but it will not show the \'z\' character and how many there
ID: 3773521 • Letter: J
Question
Java code works fine but it will not show the 'z' character and how many there are. Problem comes from Java an introduction to problem solving and programing 7th edition. Chapter 7 Programing Problem 1
import java.util.Scanner;
public class C7P1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int array[] = new int[26];
String line = "",keepOn;
int i;
char ch;
int counter=0;
do
{
System.out.println(" Put in a line finished with a period(.)");
line= keyboard.nextLine();
line=line.toLowerCase();
int allLetters= line.length()-1;
while (counter<allLetters)
{
ch=line.charAt(counter);
if(ch==' '||ch>='0' &&ch<='9')
counter++;
else
{
array[getIndex(line.charAt(counter))]++;
counter++;
}
}
for (i=0, ch='a'; ch<'z'; ch++,i++)
if(array[i]!=0)
System.out.println (ch+" "+array[i]);
System.out.println(" Continue? 'y'[ENTER]'y'[ENTER] or 'n' [ENTER]'n'[ENTER]");
keyboard.nextLine();
keepOn = keyboard.nextLine();
if(keepOn.equals('y'))
{
line="";
counter=0;
for(int K=0;K<26;K++)
array[K]=0;
}
}
while (keepOn.equals ("y"));
}//end main
public static int getIndex(char ch)
{
return (int)ch-'a';
}
}//end class
Explanation / Answer
The issue with z character is because in the last for loop, it should be ch<='z' rather than simple ch<'z' .
Corrected full code is shown below :
import java.util.Scanner;
public class C7P1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int array[] = new int[26];
String line = "",keepOn;
int i;
char ch;
int counter=0;
do
{
System.out.println(" Put in a line finished with a period(.)");
line= keyboard.nextLine();
line=line.toLowerCase();
int allLetters= line.length()-1;
while (counter<allLetters)
{
ch=line.charAt(counter);
if(ch==' '||ch>='0' &&ch<='9')
counter++;
else
{
array[getIndex(line.charAt(counter))]++;
counter++;
}
}
for (i=0, ch='a'; ch<='z'; ch++,i++)
if(array[i]!=0)
System.out.println (ch+" "+array[i]);
System.out.println(" Continue? 'y'[ENTER]'y'[ENTER] or 'n' [ENTER]'n'[ENTER]");
keyboard.nextLine();
keepOn = keyboard.nextLine();
if(keepOn.equals('y'))
{
line="";
counter=0;
for(int K=0;K<26;K++)
array[K]=0;
}
}
while (keepOn.equals ("y"));
}//end main
public static int getIndex(char ch)
{
return (int)ch-'a';
}
}//end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.