Counting characters in a Character array - JAVA - java

First off i am pretty fresh when it comes to java. My program is supposed to ask the user for strings and print what they just put in. It is then supposed to change all characters to lowercase and remove all spaces from the strings and print this. After this, it is supposed to print a character array of the alphabet and use an asterisk (*) to show each time a character occurs in the string (I dont even know where to start here). Right now it just prints the String in an array(not correct). This is what I have so far. It will print either the string with no spaces or the original but not both. My object/array naming is atrocious and i apologize in advance. Any guidance would be greatly appreciated
EDIT: here is the question
In this assignment you are to write a program that will do the following:
Ask the user to input a positive integer m, and then read that integer. Use a
Scanner object declared in main to read this integer.
Call a method that will ask the user to input m strings. As the strings are
read, they should be concatenated into a single string st. After reading the m strings and forming the single string st, the method should return st. NOTE: This method will have two parameters, an int to receive m and a Scanner object to receive the Scanner object declared in main.
In main print the concatenated string received from the method.
In main convert the String object to lower case.
In main convert the lower case String object to an array of char. (All letters
will be lower case.)
In main print the character array just created. (Requires a looping structure.)
Call a method that will compress the character array in the following way.
The method will count the letters of the alphabet in the array, create a new array whose size is equal to that count, and copy only the letters of the original array into the new array. Return the new array.
In main declare an integer array of size 26. Call a method with two parameters, a character array x (which will contain only lower case letters, and an integer array z that will receive the one declared in main). The method will set all entries in the integer array to zero. It will then process through the lower case letter array and count the number of times each letter occurs. HINT: z[x[i]-97]++ can do the counting. The ASCII code for a is 97, so if x[i] is ‘a’, then z[0] will be incremented. ‘b’ would cause z[1] to be incremented, etc. The integer array now contains a frequency distribution for the letters in the array of lowercase letters.
Call a method with one integer array parameter (which will receive the frequency distribution array) and print each letter on a new line followed by the number of stars equal to the integer value in that array element. This must be neatly aligned. Hint: if i is an index with 0 ≤ 𝑖 ≤ 25, then (char)(i+97) is a lower case letter of the alphabet.
package lab6;
import java.util.Scanner;
public class Lab6 {
public char sent[];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of strings you want: ");
int m = input.nextInt();
Lab6 loo = new Lab6();
loo.print(loo.loop(m));
}
public String loop(int m) { //print the string that was entered
String total = " ";
for (int i = 1; i <= m; i++) {
Scanner input = new Scanner(System.in);
System.out.println("enter string: " + i);
String st = input.nextLine();
total += st + "";
}
System.out.println(total);
return total;
}
public void print(String ht) { //print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
for (int i = 0; i < sent.length; i++) {
System.out.println(sent[i]);
}
}
}

Sounds like computer science is not your cup of tea. I Strongly recommend you refactor this code and try to figure out why it does what it does.
public void print(String ht) { // print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
int[] alphabet = new int[26];
//set all values to 0
for(int i = 0 ; i < alphabet.length ; i++){
alphabet[i] = 0;
}
//Loop through all characters and increment corresponding value
for(int i = 0 ; i < sent.length ; i++){
alphabet[sent[i] - 97]++;
}
//Print character + asterisk for each time the character is used
for(int i = 0 ; i < alphabet.length ; i++){
System.out.print((char)(i + 97) + ": ");
for(int nChars = 0 ; nChars < alphabet[i] ; nChars++){
System.out.print("*");
}
System.out.println();
}
}

Related

How to search for strings using method indexOf

14.11 (Searching Strings) Write an application that inputs a line of text and a search character and uses String method indexOf to determine the number of occurrences of the character in the text.
14.12 (Searching Strings) Write an application based on the application in Exercise 14.11 that inputs a line of text and uses String method indexOf to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.
My problem now is that how can I determine occurrence of each letter in a word. For example, the word "occurrence", how many times each letter occurred in this word.
I've written my code to the best of my understanding, and my code can display the characters and returns their indexes in a tabular form. But that is not exactly what the questions required.
import java.util.*;
public class Searching
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Text: ");
String text1 = input.nextLine();
char[] text2 = text1.toCharArray();
System.out.println("Character Index");
for(int i = 0; i < text2.length; i++)
{
System.out.printf("%s%12d%n", text2[i],text1.indexOf(text2[i], i));
}
}
}
I want the actual output to be in a tabular format. The word "occurrence", my code should display each letter and how many times it occurred.
LETTER FREQUENCY
o 1
c 3
u 1
r 2
e 2
n 1
Is it ok if you used a HashMap? Here's the solution for 14.12:
Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
//So we only have to find lower case chars
String input = in.nextLine().toLowerCase();
//Add every single character in the word
//We use a LinkedHashMap instead of a HashMap to retain character order during printing.
LinkedHashMap<Character, Integer> characterCount = new LinkedHashMap<>();
for(int i = 0; i < input.length(); i++) {
characterCount.put(input.charAt(i), 0);
}
//Iterate from every character ranging from a - z
//It would be more ideal to iterate only over the characters
//in the word. But your requirement asked to iterate over the alphabet.
for(int i = 'a'; i <= 'z'; i++) {
//This is the character we are currently searching for
Character searchingFor = (char)i;
int startingIndex = 0; int foundIndex = 0;
//Search for the character in the string FROM a specfic index (startingIndex in this case)
//We update startingIndex to a bigger index in the string everytime we find the character.
while((foundIndex = input.indexOf(searchingFor, startingIndex)) != -1) {
//it must be the index+1 so the next time it checks after the found character.
//without the +1, it's an infinite loop.
startingIndex = foundIndex + 1;
//Update count to the current value + 1
characterCount.put(searchingFor, characterCount.get(searchingFor) + 1);
}
}
//Print the results
for(Character c : characterCount.keySet()) {
System.out.printf("%s%12d%n", c, characterCount.get(c));
}
in.close();
Console output for the word "occurence":
Enter text: occurence
o 1
c 3
u 1
r 1
e 2
n 1

My program is printing ascii code instead of the actual letters

I can't believe i've gotten this far. My problem is my output. This program is suppose to take input from the user and increment each letter by 2. So after taking the String from the user I turn there message into a char array. then while outputing it I added 2 to each letter. and my ouput is acssii numbers. I need it to be the actual letter. how do I do this?
import java.util.*;
public class Encryption {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String userMessage = " ";
Scanner input = new Scanner (System.in);
System.out.print ("Please enter your Message:");
userMessage = input.nextLine().toUpperCase();
char arr[] = userMessage.toCharArray();
for (int i=0; i< arr.length;i++){
System.out.print(arr[i] + 2);
}
}
}
Example input : "Thank you"
Example output : 867467807734918187
Please explain to me why this is happening.
You may try casting the incremented value to char. Also, we can use the modulus operator to make sure that letters wrap around appropriately, e.g. Z should become B:
String userMessage = "ALFXYZ";
char arr[] = userMessage.toCharArray();
for (int i=0; i< arr.length;i++) {
int nextNum = 65 + (arr[i] + 2 - 65) % 26;
System.out.print((char)nextNum);
}
Demo
Your current code, as you wrote it, is printing numbers because of the casting rules.
Java cannot know ahead of time that arr[i] + 2 will be within the bounds of char (0-65535) so it will treat that expression as a number.
If you're sure the value of arr[i]+2 will never exceed this range then you can safely cast back to a char:
System.out.print((char)(arr[i] + 2));
Java converts some primitive types automatically.
If c is a char and i is an int, then c + i will be treated as an int.
PrintStream, the type of System.out, has many overloads of print; the one chosen depends on the type of the argument.
Cast your addition back to char and it should work:
(char)(arr[i] + 2)

How to compare elements within an array and store specific elements into a separate array?

I know similar questions have been asked. I've read through them and have developed what I thought was a reasonable solution to my problem. However, when I run the code it does not perform as I think it should. I'm obviously missing something here.
I need to read in a string (a propositional logic statement) and determine how many variables it has. My thought process is: convert the string to a charArray and compare the elements. If a certain element is a letter AND is not equal to another element in the array, it is a new variable, thus adding to the variable count, and also needs to be stored in a separate array for later use.
public class PropLogic {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String statement;
int numOfVariables = 0;
System.out.println("Enter your propositional statement:");
statement = stdin.nextLine();
char[] charStatement = statement.toCharArray();
char[] variables;
variables = new char[25];
// Counts number of variables in statement
for (int i = 0; i < statement.length(); i++){
for(int j = i + 1; j < statement.length(); j++){
if(Character.isLetter(charStatement[i]) && (charStatement[i] !=
charStatement[j])){
variables[i] = charStatement[i];
numOfVariables++;
}
}
}
System.out.println("The number of variables is " + numOfVariables);
System.out.println("The variables are " + new String(variables));
}}
With input "hello" I get output of 9 variables and that the variables are "hell" when I want to be getting 4 variables that are "hello".
Why don't you use a Set. A set has the property that you can enter the same object only once into it. Here is one version:
Set<Character> set = new LinkedHashSet<>();
for(int i = 0; i< statement.length(); i++) {
set.add(statement.charAt(i));
}
System.out.println("The number of variables is " + set.size());
System.out.println("The variables are ");
set.forEach(System.out::println);
You don't need to use char array since String has the methods CharAt() and contains().
Then you have to run through your String. When you find a new letter (which mean this letter is not in the already found array), you put it in the already found array and you increment your counter. (note that the counter is useless since it as the same value as the length of the already found array). You should obtain something like this :
String statement = stdin.nextLine();
String variables = ""; //empty String
//Go through the whole String statement
for (int i = 0; i < statement.length(); i++){
//Check if this letter was not already found and it's a letter
if(!variables.contains(statement.charAt(i)) && Character.isLetter(statement.charAt(i)) ){
//Add this letter to the found ones
variables.concat(String.valueOf(statement.charAt(i)));
}
}
System.out.println("The number of variables is " + variables.length());
System.out.println("The variables are " + variables);
I see two problems:
Problem 1. Think about what happens, for example, with the "h" of "hello." You compare it, in turn, to "e", "l", "l", and "o", and for each of them, you add a new variable. What you want is to add a new variable only if ALL of the future letters are not equal to the "h." This is why you are getting 9 variables total: you add one for each of the following comparisons:
(h, e), (h, l), (h, l), (h, o)
(e, l), (e, l), (e, o)
(l, o)
(l, o)
This is also why you are getting "hell" as your final variables array. The o is never compared to anything, so never gets added to the array.
What you really want to do is go through the entire rest of the string, and check if anything is equal to the current letter. You can do this with a boolean flag. Here is pseudocode:
for i = 0 to len(charArray):
isNewVariable = isLetter(charArray[i])
for j = i+1 to len(charArray):
if charArray[i] == charArray[j]:
isNewVariable = false
if isNewVariable:
Add charArray[i] to variables
Problem 2. You are filling in the wrong index of your variables array. You want to fill in variables[numOfVariables], not variables[i]. Let's say the first and seventh letters are variables; then you want variables[0] and variables[1] to be set to the two variables, not variables[0] and variables[6], which is what your current code does.
Hope this helps! If you fix these two errors, your code will work; however, as other answers point out, this general strategy is not the best for this specific task. Incrementally adding to an array (like variables) is best done with an ArrayList; even better, a Set is exactly suited for the task of finding just the unique elements of an array.
what is happening here is, check if char exists in temp string with 'temp.indexOf(char)', it returns 1 if it exists at an index of that string and 0 otherwise.
so if 0, then add and loop to next char.
public static void main( String[] args ){
Scanner stdin = new Scanner(System.in);
String statement;
int numOfVariables = 0;
System.out.println("Enter your propositional statement:");
statement = stdin.nextLine();
char[] charStatement = statement.toCharArray();
char[] variables;
variables = new char[25];
String temp = "";
for (int i = 0; i < statement.length(); i++){
char current = statement.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
}
}
System.out.println("The number of variables is " + temp.length());
System.out.println("The variables are " + temp);
}
A key to success in writing good programs is to make sure it has as few lines of code as possible and it doesn't repeat an operation that it has already performed or that is not even needed.
If you think about your problem statement, basically, all you need to do is extract letters from a given input string and remove duplicates. With advance programming languages like Java, String operations shouldn't take more than a couple of lines of codes. If it is more than 2 lines, in most cases, it has a lot of boiler plate code.
See if the following line of code meets your objective.
Set<String> variables = Arrays.stream(statement.split("")).filter(str -> Character.isLetter(str.charAt(0))).collect(Collectors.toSet());
If you are OK with not insisting on char[] variables and use List<Character> instead, this does the job
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PropLogic {
public static List<Character> parseVariables(char[] input) {
List<Character> candidates = new ArrayList<>();
for (int i = 0; i < input.length; i++){
Character c = input[i];
if( Character.isLetter(c) && !candidates.contains(c)) {
candidates.add(c);
}
}
return candidates;
}
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter your propositional statement:");
char[] charStatement = stdin.nextLine().toCharArray();
List<Character> variables = parseVariables(charStatement);
System.out.println("The number of variables is " + variables.size());
System.out.println("The variables are " + variables);
}
}
Sample output:
Enter your propositional statement:
hello1
The number of variables is 4
The variables are [h, e, l, o]
Here's a 1-liner:
String[] variables = statement.replaceAll("[^a-z]|(.)(?=.*\\1)", "").split("(?<=.)");
This uses regex to remove (by replacing with a blank) all non-lowercase letters OR all letters that are repeated later on (ie remove dupes).
Then it splits after each letter giving you the final array of unique letters from the input.
Note that this creates a String[] rather than a char[], which you can just as easily use. If you really want a char[], you can do this:
String[] variables = statement.replaceAll("[^a-z]", "").chars()
.distinct().mapToObject(c -> (char)c).toArray();

Is there a Way I can rearrange characters in a given string using a modified set of index values?

Say I have the string: "Polish". which is indexed as: P=0,O=1, L=2, I=3, S=4, H=5
I want to be able to type something like
" word1.arrangebyindex(051423) "
and have word2 equal PHOSLI
I want to be able to type in any combination of index values and have it rearranged to a new word.
I'm trying to write a program that will rearrange a given word in the following way:
The first character of the word is followed by the last character of the word which is followed by the second character and then the second last character of the word and so on. If the given word has an odd number of characters, then the middle character is repeated again. For example, given the word "mouse" it should be encoded as "meosuu"
I suggest making a hashmap, which allows the user to enter in a letter, which would be the key and a number, which would be the value.
Once you associate all the letters with the number as a key and a value (such as P: 0 and H:5), then you can use your hashmap to create a string based on the numbers given to you.
Break each number down by digits (note that it will be more difficult to implement if a word is associated with a multiple digit number) and add to the string depending on what number you have called.
Here's the hashmap api: https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Just look at the method summary and try those. I doubt you'll need much else out of the rest of the api.
If you use HashMap then key as integer and value should be character because if string = APPLE then 0-A 1-P 2-P 3-L 4-E.
or you should go through this way:
public class ModifiedIndex {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char [] ch = str.toCharArray();
String s ="";
int i=0;
int j = str.length()-1;
if(str.length()%2 == 0)
{
for(int k = 0; k < str.length()/2; k++)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
else
{
for(int k = 0; k < str.length(); k++)
{ if(i<=j)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
}
}
}

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

Categories