JAVA ECLIPSE: spacing issue. please help. My problem is when I type the phrase \
ID: 3941110 • Letter: J
Question
JAVA ECLIPSE: spacing issue. please help.
My problem is when I type the phrase "Hello World!" I get spacing issues when the program counts how many times the letters are used.
My code however works fine for single words as seen below:
Here's my code:
import java.util.Scanner;
import java.io.*;
public class ProgrammingAssignment11 {
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
String input1=new String("");//input string
String temp;//to read strings line by line
char[] c=new char[26];//to store string in characters format
int[] a=new int[26];//to count Number of Characters
char ch,temp1 = 0;
System.out.print("Enter text: ");
{
while(input.hasNext()){
temp=input.nextLine();//used to read string
input1=input1.concat(temp);//putting temp string to main string
}
c=input1.toCharArray();//converting string to char[]
for(int i=0;i<c.length;i++){
if(Character.isDigit(c[i])) {
System.out.println();
System.exit(0);
}
if(Character.isLetter(c[i]))//to check letter is Character or not
{
if(Character.isLowerCase(c[i]))
c[i]=Character.toUpperCase(c[i]);
int index=c[i]-'A';//finding index
int b=a[index];
b++;
a[index]=b;//incrementing value in an array
temp1=(char) index;
}
}
}
for(int i=0;i<a.length;i++)
{
if(a[i] > 0){
System.out.printf(("%c: ") + ("%d"), i + 65 , a[i]);
if(i<temp1)
System.out.println();
}
}
System.out.println();
}
}
Any help would be greatly appreciated!
Enter text: D: 1 2E: 1 3H: 1 4L: 3 50: 2 6 R: 1 7W: 1 1 Enter text: D: 1E: 1H: 1L: 30: 2R: 1W: 1 2Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class ProgrammingAssignment11 {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String input = "";
int[] a=new int[26];//to count Number of Characters
System.out.print("Enter text: ");
input = sc.nextLine(); // reading user input
char[] c = input.toCharArray();//converting string to char[]
for(int i=0;i<c.length;i++){
if(Character.isDigit(c[i])) {
System.out.println();
System.exit(0);
}
if(Character.isLetter(c[i]))//to check letter is Character or not
{
if(Character.isLowerCase(c[i]))
c[i]=Character.toUpperCase(c[i]);
int index = c[i]-'A';//finding index
int b=a[index];
b++;
a[index]=b;//incrementing value in an array
}
}
for(int i=0;i<a.length;i++)
{
if(a[i] > 0){
System.out.printf(("%c: ") + ("%d"), i + 65 , a[i]);
}
}
System.out.println();
}
}
/*
Sample run:
Enter text: THis is a programming
A: 2G: 2H: 1I: 3M: 2N: 1O: 1P: 1R: 2S: 2T: 1
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.