frequency of a letter in a string using arrays - java

In this program I have been having trouble to get the terminal window I suspect it might be a runtime error .I am using blue J btw. Also I dont understand why the code used this
f[ch-'A']++;
Please help out with a tracing for this program.
This is the code:
import java.util.*;
public class frequency
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int f[]= new int[26];
System.out.println("enter a string");
String input = sc.nextLine();
input= input.toUpperCase();
for(int i=0; i<input.length();i++)
{
char ch=input.charAt(i);
if (Character.isLetter(ch))
f[ch-'A']++;
}
System.out.println("Characters Frequency");
for(int i=0;i<26;i++)
{
if( f[i]!=0)
{
System.out.println((char) (i+'A') + "\t\t" + f[i]);
}
}
}
}

Because it is converting the text to uppercase
input= input.toUpperCase();
each char can have the ascii value of A subtracted (see https://www.asciitable.com/) to obtain an index into the array.
'B' - 'A' == 1 etc
test
enter a string
stupid sod
Characters Frequency
D 2
I 1
O 1
P 1
S 2
T 1
U 1

Related

Number's print in its sizes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to Print something like this
But i face Runtime error and wrong answer
input:
153
output:
1:1
5:55555
3:333
get an integer and print each number in its size
import java.util.Scanner;
public class q9774 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (char value : E) {
System.out.print(value + ": ");
if (value == 0) continue;
else {
for (int i = 0; i < Integer.parseInt(String.valueOf(value)); i++) {
System.out.print(value);
}
System.out.println();
}
}
}
}
Since Java-11, you can use String#repeat to repeat a string for a given number of times.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (char value : entry.toCharArray()) {
System.out.print(value + ": ");
System.out.println(String.valueOf(value).repeat(Character.getNumericValue(value)));
}
}
}
A sample run:
153
1: 1
5: 55555
3: 333
An alternative way to process each character can be to split the string on each character and then repeat it for number of times equal to its numeric value.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (String s : entry.split("")) {// Split on each character
System.out.print(s + ": ");
System.out.println(s.repeat(Integer.parseInt(s)));
}
}
}
Here is one way of doing it.
converts the int to a String and then to a char[] array
prints the character followed by itself repeated.
any character digit - '0' is a numeric value of the same quantity represented by the character. So the character '7' has the int value of '7' - '0' or 7.
int i = 153;
for (char c : Integer.toString(i).toCharArray()) {
System.out.printf("%c:%s%n", c, (c+"").repeat(c-'0'));
}
Prints
1:1
5:55555
3:333
I added a nested loop for each digit and I repeat that nested loop according to index of value in string by j <= i; condition:
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (int i = 0; i < E.length; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(E[i]);
}
System.out.println();
}

Write a program that will read a line of text, and will display all letters in the text along with the number of times the letter appears in the text

I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.
what I have so far is:
package as10;
import java.util.*;
public class as
{
private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();
for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();
System.out.println("Letter Frequencies: ");
countLetters(letterString);
break;
}
kbd.close();
}
}
so, basically, you want to opt out all chars if counter is 0.
In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.
Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.
Does it sound fair ? :)

By using while/for loop, how to subtract ONLY the uppercase of a line input by users?

Here is my code, i used is.upperCase to check but it doesn't seem to work. And i have trouble concatenating all the uppercases together. Any suggestion and help would be appreciated!
import java.util.Scanner;
public class UpperCase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
int i = 0;
while (i < str.length() - 1) {
if(Character.isUpperCase(i)) {
char upperLetter = str.charAt(i);
}
Object outputLetter = str.charAt(0) + str.charAt(i++);
char upperLetter = str.charAt(i++);
}
System.out.println("The uppercase letters are:" );
}
}
I guess below would solve your problem.
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.nextLine();
char[] cr = str.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<cr.length;i++){
if(Character.isUpperCase(cr[i])){
stringBuffer.append(cr[i]);
}
}
System.out.println("The uppercase letters are:" + stringBuffer);
First, your idea is correct, but the way you did implement has some mistakes
1. isUperCase of i -> Wrong
2. outputLetter should be declare outside the loop to advoid re-init data
3. outputLetter should be something like outputLetter += anUpperCase
4. finally, refer this bellow code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
in.close();
int i = 0;
String result = "";
while (i < str.length() - 1) {
char aChar = str.charAt(i);
if (Character.isUpperCase(aChar)) {
result += aChar;
}
i++;
}
System.out.println("The uppercase letters are: " + result);
}

error in my Java

So currently im trying to do a java project and have seen a few answers on this on other websites but im having trouble understandign them. i need to do this:
"Write a program that prompts the user to input a string of words, then counts and displays the number of times each letter in the alphabet appears in the string. It is not necessary to distinguish between uppercase and lowercase letters. Your output should be formatted as follows:
Letter A count = xx
Letter B count = xx
....
Letter Z count = xx"
and this is what I have so far:
import java.util.Scanner;
public class Unit9 {
public static void main(String [] args )
{
int array[] = new int[26];
for (int i = 0; i < array.length; i++)
{
array[i] = 0;
}
Scanner Keyboard = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string.");
userInput = Keyboard.next().toLowerCase();
for (int i = 0; i < userInput.length(); i++)
{
char ch = userInput.charAt(i);
if (ch >= 'a' && ch <= 'z') {
array[ch - 'a'] ++;
}
}
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + array[ch-'a']);
}
}
}
but when i enter "hello" (without the quotes) i end up getting this:
Please enter a string.
hello
979899100102102103105105106107110109110112112113114115116117118119120121122
what is happening? what am i doing wrong?
EDIT: actually, i just realized something else... it stops detecting when there is a space in the user input meaning that it only detects the first word. how would I add detection for a space as well?
The reason why it only detected the first word is because you entered:
userInput = Keyboard.next().toLowerCase();
instead of
userInput = Keyboard.nextLine().toLowerCase();
nextLine() reads the whole line entered while next() only reads the first word.
You are using the + operator between a char and an int on this line:
System.out.print(ch + array[ch-'a']);
This gives you a number as a result, which is then inputted into System.out.print taking int as input, therefor printing the number itself. You also have no spacing (or use println), so it appears to be one long line of numbers.
Try this for your last loop:
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + ": "+ array[ch-'a']+" ");
}
It will now no longer be seen as addition, but rather concatination and show as a string of "letter: amount", one after another for the entire alphabet.

How to make equals read a character

So what I need help on is that I have this code and I do not know how the if statements can read ",", ".", and "$". I think the String X should be Char instead of String but I do not know how I could change my String X = in.next(); with char[] arr = new char[] and this statement need to be as an input statement! Thank you for helping me and after answering could you write what kinds of things I could do to make my questions better?
So what this code is supposed to do is that for example input is say &&&&&& and 456 then the output is supposed to be*** 456 so meaning &&&&&& = ** and as many numbers there are meaning length the 's go away so * -> ***456
and if input contains "," for example input is &&&,&&&&&(anywhere is fine for ",") and 10000 then output is 10,000 and so on with "." that puts decimal point where it is placed and round up to that point and "$" just puts a dollar sign in front of the numbers
import java.util.Scanner;
public class printFormatting
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the &'s and ,'s");
String X = in.next();
System.out.println("Enter the numbers");
String Y = in.next();
int lengthX = X.length();
int lengthY = Y.length();
if (X.equals(",") && X.equals("."))
{
System.out.println("Works , && .");
//This is to see if , and . both are being able to be seen by the code
}
else if (X.equals(","))
{
System.out.println("Works ,");
//This is to see if , can be seen
}
else if (X.equals("."))
{
System.out.println("Works ,");
//same
}
if (X.equals("$"))
{
System.out.println("Works $");
}
for (int z = lengthX-lengthY; z > 0;)
{
System.out.print("*");
z--;
}
System.out.println(Y);
}
}

Categories