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);
Related
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();
}
}
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));
I wrote a code here to do the following:
Prompt the user for how many numbers are going to be entered. We called this value userRequest.
So, userRequest times we do the following:
read a String. This String will have the form: a mixture of digits and letters.
return the integers of the String and the letters separated.
but in the returning code, I scanned the string character by character, so it printed each input separately. But, my question is how can I print the numbers together as one integer and the letters together as on string. (I think it needs arrays, but I couldn't call an array when it inside a loop)
import java.util.*;
public class Program8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int userRequest;
int returnNum;
System.out.print("How many numbers do you wish to enter? ");
while (!scan.hasNextInt()){
System.err.print("Please try again, with digits only: ");
scan.next();
}//while
userRequest = scan.nextInt();
int sortingNum = 1;
String str;
char ch;
str = scan.nextLine();
for (int i = 0; i < userRequest; i++){
System.out.print("* Please enter a string #" + sortingNum + ": ");
str = scan.nextLine();
System.out.println("- String #" + sortingNum++ + " = " + str);
for (int j = 0; j < str.length(); j++){
ch = str.charAt(j);
if ((ch + 0) >= 48 && (ch + 0) <= 57){
int digit = ((ch + 0) - 48);
System.out.println(digit);
}
}
System.out.println();
for (int k = 0; k < str.length(); k++){
if (str.toLowerCase().charAt(k) >= 'a' && str.toLowerCase().charAt(k) <= 'z')
System.out.println(str.charAt(k));
}
}//for
}//main
}//Program8
For the number:
Add the logic to multiply a variable by 10 and add the digits extracted.
For the string:
Add the logic to append the characters to a stringbuilder object.
Code:
int finalNumber = 0;
for (int j = 0; j < str.length(); j++){
ch = str.charAt(j);
if ((ch + 0) >= 48 && (ch + 0) <= 57){
int digit = ((ch + 0) - 48);
finalNumber = finalNumber*10 + digit;
//System.out.println(digit);
}
}
System.out.println(finalNumber);
System.out.println();
StringBuilder finalString = new StringBuilder();
for (int k = 0; k < str.length(); k++){
if (str.toLowerCase().charAt(k) >= 'a' && str.toLowerCase().charAt(k) <= 'z') {
//System.out.println(str.charAt(k));
finalString.append(str.charAt(k));
}
}
System.out.println(finalString.toString());
// I have a program where I am supposed to count unique characters, only letters and numbers and don't count repeating numbers or letters. However, I have a problem finding out a way for the program not to count spaces and symbols such as "!" "#" "#" "$". So If i type in Hello! I only want the program to say "4", but it says "5" because it counts the exclamation point. Here is my code so far:
public static int countUniqueCharacters(String text1) {
int count = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.substring(0, i).contains(text1.charAt(i) + ""))
System.out.println();
else
count++;
}
return count;
}
In your else block add a condition that the count will be incremented only if the given character is a letter or a digit.
if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
count++;
}
In your example:
public static int countUniqueCharacters(String text1) {
int count = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.substring(0, i).contains(text1.charAt(i) + "")) {
System.out.println();
} else if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
count++;
}
}
return count;
}
here's a sample code written in C# try and understand it. It compares with ascii and adds in a list
string input = Console.ReadLine();//input
List<char> CountedCharacters = new List<char>();
for (int i = 0; i < input.Length; i++)
{ //checking for numerics //checking for alphabets uppercase //checking for alphabets lowercase
if ((input[i] >= 45 && input[i] <= 57) || (input[i] >= 65 && input[i] <= 90) || (input[i] >= 97 && input[i] <= 122))
{
bool AlreadyExists = false;
for (int j = 0; j < CountedCharacters.Count; j++)
{
////checking if already exists
if (CountedCharacters[j]==input[i])
{
AlreadyExists = true;
break;
}
}
////adding in list if doesnt exists
if (!AlreadyExists)
{
CountedCharacters.Add(input[i]);
}
}
}
for (int i = 0; i < CountedCharacters.Count; i++)
{
Console.WriteLine(CountedCharacters[i]);
}
Try this one using regex. You can add and remove the characters you need from the expression to count what you need.
public static int countUniqueCharacters(String text1) {
String newText = text1.replaceAll("[^A-Za-z0-9()\\[\\]]", "");
Set<Character> tempSet = new HashSet<>();
for (char item : newText.toCharArray()) {
tempSet.add(item);
}
return tempSet.size();
}
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.