How to capitalize the common letters of two words? - java

I'm trying to capitalize the common letters of two words. Does anyone know why my code doesn't work?
It says:
Main.java:22: error: cannot find symbol
char character = words.charAt(i);
^
symbol: method charAt(int)
location: variable words of type String[]
The code is:
int word2;
int space_count = 0;
//get input
System.out.println ("Input two words: ");
int word = sameletters.nextInt();
String words[] = new String[word];
//find the begining of the second word
for(int i = 0, n = words.length; i<n; i++)
{
char character = words.charAt(i);
if(Character.isWhitespace(character))
{
word2 = i + 1;
space_count++;
}
}
//validate the input.
for(int i = 0, n = words.length; i<n; i++)
{
if(space_count != 1)
{
System.out.println ("MUST CONTAIN 2 WORDS\n");
break;
}
}
//loop for the first word
for (int i = 0, n = word2 - 1; i < n; i++)
{
//loop for the second word
for (int j = word2, x = words.length; j < x; j++)
{
//compare the letters
if(words[i] == words[j])
{
words[i] = words[i].toUpperCase();
words[j] = words[j].toUpperCase();
}
}
}
//print output
System.out.println ("\n" + words);
sameletters.close();
}
}

Related

Crossed words game in Java

I have been stuck on this exercise for 2 weeks now, hopefully someone can help...
So basically the user starts by providing the number of lines and columns and the corresponding crossed words table(which is a 2d char array) , then inputs the number of words and the words that have to be detected in that board.
The program is supposed to print the table that was given but with every non-word substituted for zeros.
An example:
Input:
4 5
GBCDP
AGGGM
MYIEU
ENBHJ
2
GAME
JUMP
Should output:
G000P
A000M
M000U
E000J
My problem is still in the method for finding the words...
this is my code(it's commented to be easier to understand)
NOTE: the words cannot be found diagonally... also I am missing the part of the program that's supposed to substitute non-words for zeros, because I still can't find the words
import java.util.Scanner;
class game {
private int rows;
private int cols;
private char m[][];
game(int r, int c)
{
rows = r;
cols = c;
m = new char[r][c];
}
//read the game
public void read(Scanner in) {
for (int i=0; i<rows; i++) {
m[i] = in.next().toCharArray();
}
}
//writes the game
public void write() {
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols; j++)
{
System.out.print(m[i][j]);
}
System.out.println();
}
}
//finds the words
public void find(String word) {
for(int i = 0; i < rows; i++)
{
if(word.equals(new String(m[i]))){
System.out.print(i);
}
}
for(int z = 0; z < cols; z++)
{
if(word.equals(new String(m[z]))) {
System.out.print(z);
}
}
}
}
public class wordg {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
game j = new game(rows,columns);
j.read(scan);
//j.write();
int wordnumber = scan.nextInt();
String words[] = new String[wordnumber];
for(int i = 0; i < wordnumber; i++)
{
words[i] = scan.nextLine();
}
for(int w = 0; w < words.length; w++)
{
j.find(words[w]);
}
}
}
Thanks!
How to fix the code
In this part of the answer, I will try to give a step-by-step guide on how to make your code work properly:
The first problem with your code is that you are using the rows instead of the columns, although you obviously want to use columns. This can be done like this:
String col = "";
for(int i = 0; i < rows; i++) {
col += m[i][z];
}
The next problem is that you also have to search for the reversed words. You can do that by just calling the method find with the reversed words also:
for(int w = 0; w < words.length; w++)
{
j.find(words[w]);
j.find(j.reverse(words[w]);
}
The reverse-method could look like this:
public String reverse(String word) {
String result = "";
for(int i = word.length() - 1; i >= 0; i--) {
result += word.charAt(i);
}
return result;
}
After this, your find-method should work.
To output the grid like you want it to look like, we will have to save, where we found a word. This can be done like this:
if(word.equals(new String(m[i]))){
System.out.println("Word found in row: " + i);
for(int j = 0; j < cols; j++) {
test[i][j] = true;
}
}
test is a boolean-array initialized with false in the constructor.
Now we just have to change the write-method:
//writes the game
public void write() {
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols; j++)
{
if(test[i][j]) { //Only print found words, otherwise print "0"
System.out.print(m[i][j]);
}
else {
System.out.print("0");
}
}
System.out.println();
}
}
At this point the program should produce the output you want it to produce.
Possible improvements
If you want to improve your find-method, you could make the program recognize words inside a row or a column, for example recognize the word "YOU" in this grid:
AAYOUA
AAAAAA
AAAAAA
AAAAAA
This can be done like this:
public void find(String word) {
for(int i = 0; i < rows; i++) {
int index = new String(m[i]).indexOf(word); //Index were found word starts (-1 if row/col doesn't contain the word)
if(index >= 0) {
System.out.println("Word found in row: " + i); //Added some information for the user
for(int j = index; j < index + word.length(); j++) {
test[i][j] = true; //Save that word was found in this "cell"
}
}
}
for(int z = 0; z < cols; z++) {
String col = "";
for(int i = 0; i < rows; i++) { //Get column
col += m[i][z];
}
int index = col.indexOf(word);
if(index >= 0) {
System.out.println("Word found in col: " + z);
for(int j = index; j < index + word.length(); j++) {
test[j][z] = true;
}
}
}
}
Some other suggestions:
Class-names should begin with an uppercase-letter
Try to always use the same indentation
Try to always use the same "bracket-style"
(I changed this for you in the final code.)
Final code
All in all your code looks like this now:
Game.java
import java.util.Scanner;
public class Game { //Classes start with uppercase
private int rows;
private int cols;
private char m[][];
private boolean test[][]; //Purpose: test if "cell" where word was found
Game(int r, int c) {
rows = r;
cols = c;
m = new char[r][c];
test = new boolean[r][c];
}
//read the game
public void read(Scanner in) {
for (int i=0; i<rows; i++) {
m[i] = in.next().toCharArray();
}
}
//writes the game
public void write() {
for(int i = 0; i < rows;i++) {
for(int j = 0; j < cols; j++) {
if(test[i][j]) { //Only print found words, otherwise print "0"
System.out.print(m[i][j]);
}
else {
System.out.print("0");
}
}
System.out.println();
}
}
//finds the words
public void find(String word) {
for(int i = 0; i < rows; i++) {
int index = new String(m[i]).indexOf(word); //Index were found word starts (-1 if row/col doesn't contain the word)
if(index >= 0) {
System.out.println("Word found in row: " + i); //Added some information for the user
for(int j = index; j < index + word.length(); j++) {
test[i][j] = true; //Save that word was found in this "cell"
}
}
}
for(int z = 0; z < cols; z++) {
String col = "";
for(int i = 0; i < rows; i++) { //Get column
col += m[i][z];
}
int index = col.indexOf(word);
if(index >= 0) {
System.out.println("Word found in col: " + z);
for(int j = index; j < index + word.length(); j++) {
test[j][z] = true;
}
}
}
}
public String reverse(String word) {
String result = "";
for(int i = word.length() - 1; i >= 0; i--) {
result += word.charAt(i);
}
return result;
}
}
WordG.java
import java.util.Scanner;
public class WordG {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
Game j = new Game(rows,columns);
j.read(scan);
int wordnumber = scan.nextInt();
scan.nextLine(); //To clear the scanner
String words[] = new String[wordnumber];
for(int i = 0; i < wordnumber; i++) {
words[i] = scan.nextLine();
}
for(int w = 0; w < words.length; w++) {
j.find(words[w]);
j.find(j.reverse(words[w])); //You also have to search for reversed words!
}
j.write(); //Write grid after searching
}
}
(I added comments on the right where I changed your code to explain what I did.)
Output
With your example-input, this code creates the following output:
Word found in col: 0
Word found in col: 4
G000P
A000M
M000U
E000J
And with the added functionality, the input
5 5
SHARK
AYOUB
MABCD
EABCD
ABCDE
3
YOU
ME
SHARK
gives the output
Word found in row: 1
Word found in col: 0
Word found in row: 0
SHARK
0YOU0
M0000
E0000
00000

How to compute the frequency of occurrence of '+' and '++' in Java?

I want to calculate the frequency of the occurrence of all the operators from an input text file. The file contains the operators + and ++. How can I distinguish their respective frequency, as my program treats ++ as 2 distinct + operators rather than 1 ++?
Here is my code (input7.txt is a test file):
public static void main(String[] args) throws IOException {
String string = new String(Files.readAllBytes(Paths.get("input7.txt"))); //String to be counted
int frequencyArray[] = new int[string.length()];
int frequencyArray2[] = new int[string.length()];
char stringArray[] = string.toCharArray(); //Array of characters
int i, j;
//Count characters
for (i = 0; i < string.length(); i++) {
frequencyArray[i] = 1;
//frequencyArray2[i] = 1;
for(j = i + 1; j < string.length(); j++)
{
if(stringArray[i] == stringArray[j])
{
frequencyArray[i]++;
stringArray[j] = '0'; //To avoid revisiting a character
}
}
}
//Display results
System.out.println("Characters and their corresponding frequencies");
for (i = 0; i < frequencyArray.length; i++) {
if (stringArray[i] != ' ' && stringArray[i] != '0') {
System.out.println(stringArray[i] +"-" + frequencyArray[i]);
}
}
}
This works for me:
String s = "sdfasd++ sdfadsf+asdf sdf++sadfasdf++sadfsdf+asdfasdf++";
// create Set with all distinct characters
Set<Character> chars = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
chars.add(s.charAt(i));
}
// count distinct characters and put Results in HashMap
Map<Character, Integer> counts = new HashMap<Character, Integer>();
for (Character c : chars) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c)
count++;
}
counts.put(c, count);
}
// Count double-Character-Operators like this
int countPlusPlus = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.substring(i, i + 2).equals("++"))
countPlusPlus++;
}
// Calculate totals like this
int singleplusTotal = counts.get('+');
System.out.println("Single Plus total" + singleplusTotal);
System.out.println("Double Plus total" + countPlusPlus);
System.out.println("Only single Plus" + (singleplusTotal - countPlusPlus * 2));

printing two different loops on the same line

hello everyone I can't figure out how to print these two statements on the same line.
for(int index = 1; index < word.length(); index++){
System.out.printf("\n%s", builder.charAt(index));
}
for(int index = word.length()-2; index >= 0; index--){
System.out.printf("\n%s%s",space ,backWards.charAt(index));
}
my objective is to give this method a word and it prints the rectangle, for example:
word = java
it will print:
java
a v
v a
avaj
please try to keep it as simple as possible because I'm still a beginner
The only way to print string vertically, is to loop through it's characters and print one of them on each line
String str = "JAVA";
System.out.println(str);
for(int i=1; i<str.length()-1; i++){
System.out.print(str.charAt(i));
for(int j=1; j<str.length()-1; j++){
System.out.print(' ');
}
System.out.println(str.charAt(str.length()-1-i));
}
for(int i=0; i<str.length(); i++){
System.out.print(str.charAt(str.length()-1-i));
}
Here is one way to do it:
String word = "java";
// print first line
System.out.println(word);
String spaces = getSpacesFor(word.length() - 2);
// print out middle lines
for(int i = 1; i < word.length() - 1; i ++) {
// first character is from the normal word order
String s = "" + word.charAt(i);
// add middle spaces
s += spaces;
// add last character which is backwards order
s += word.charAt(word.length() - i - 1);
// print out
System.out.println(s);
}
// print backwards word
for(int i = 0; i < word.length(); i ++) {
System.out.print(word.charAt(word.length() - i - 1));
}
getSpacesFor would be a method like:
public static String getSpacesFor(int num) {
String s = "";
for(int i = 0; i < num; i ++) {
s += " ";
}
return s;
}

Common length of strings in java

In this java program everything works fine but at the last i have to get the number of words matched in length of character but i cant how to get it?
Scanner input = new Scanner(System.in);
String s1 = "Enter the name 1:";
System.out.println(s1);
s1 = input.next();
String s2 = "Enter the name 2:";
System.out.println(s2);
s2 = input.next();
if (s1.equals(s2)) {
System.out.println("They match");
} else {
System.out.println("They dont match");
}
char[] c = s1.toCharArray();
char[] d = s2.toCharArray();
for (char i = 0; i < c.length; i++) {
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
System.out.println("The number of letters matched are :" + c[i]);
}
}
}
System.out.println("The number of letters matched are :" + c.length);
Use a counter
int counter = 0 ;
for (char i = 0; i < c.length; i++) {
boolean found = false;
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
found = true;
System.out.println("The number of letters matched are :" + c[i]);
break;
}
}
if(found){
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);
char[] c = s1.toCharArray();
char[] d = s2.toCharArray();
int count = 0;
for (char i = 0; i < c.length; i++) {
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
count++;
}
}
}
System.out.println("The number of letters matched are :" + count);
I think this is what you are looking for.
You need to count the number of matches in your loop, then after looping display the number of letters that are in both arrays.
If the objective is to get the number of common characters between two strings, then one approach is to convert both strings to character sets and do set intersection between the two sets and get its size.
If you want the number of times a character in s1 also appears in s2:
int counter = 0;
for (int i=0; i<s1.length(); i++) {
if (s2.indexOf(s1.charAt(i)) >= 0) {
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);
If instead you want the number of distinct characters shared by s1 and s2:
Set<Character> set = new HashSet<>();
int counter = 0;
for (int i=0; i<s1.length(); i++) {
set.add(s1.charAt(i));
}
for (int j=0; j<s2.length(); j++) {
if (set.contains(s2.charAt(j))) {
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);

Getting each letter in a String only once

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.

Categories

Resources