Cannot compare Chars in java, code running but results don't come - java

/* Program to search a character in a sentence and tell the occurrence of
that character in that sentence and also prints all the indexes. */
package com.shobhit.string1;
import java.util.Scanner;
public class StringSearch1
{
public static void main(String args[])
{
String sentence;
char c; // takes first character of input
char duplicate; // finds duplicates of c in code
int length; // find sentence length
int index; // index of character in sentence
int numberOfOccurrence = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
sentence = in.nextLine();
System.out.println("Enter a character you want to find in the sentence:");
c = in.next().charAt(0);
length = sentence.length();
System.out.println("The indexes of the character are:");
for (int i = 0; i >= length - 1; i++)
{
duplicate = sentence.charAt(i);
if (c == duplicate)
{
numberOfOccurrence = numberOfOccurrence + 1;
index = sentence.indexOf(c);
System.out.println("Index is:" + index);
}
}
System.out.println("The number of times " + c + " has occured is:"
+ numberOfOccurrence);
}
}
Unexpected output:
Enter a sentence:
I don't want to type another long sentence
Enter a character you want to find in the sentence:
t
The indexes of the character are:
The number of times t has occured is:0

You want this look like this
for(int i = 0 ; i < length; i++)
instead of
for(int i = 0 ; i >= length -1; i++)
because it is never going to be iterate for length > 1 cases

Your condition for the "for" loop is wrong. It should be i < length or i < length - 1

for(int i = 0 ; i>=length -1; i++)
Can you try
for(int i = 0 ; i<=length -1; i++)

Related

not getting correct input for checking for duplicates

for the problem, i am required to take in 10 integers, and then print out the unique numbers. My problem solving approach for this was to scan all the numbers behind the one we are checking to see if there are any duplicates. here's the code I have so far. if i enter in numbers like "1234567891", it only will print "pl: 1" because I add the first number before running the algorithm. Any hypothesis on why it's not working?
//setup
Scanner input = new Scanner(System.in);
String text = input.nextLine();
text = text.replaceAll("\\s",""); //remove all spaces
int[] intDigits = new int[10];
//turn the string into an int array
for (int i = 0; i < 10; i++){
intDigits[i] = text.charAt(i) - '0';
}
input.close();
//add the first number since it will always be unique with my algorithm
String pl = intDigits[0] + " ";
//check every number behind the one we are checking, if all the numbers are not equal to the one we are checking, then add it to the string of unique numbers.
for (int i = 1; i < 10; i++) {
int count = 0;
for (int j = i-1; j >= 0; j--) {
if (intDigits[i] != intDigits[j]) {
count++;
}
}
if (count == i-1) {
pl += intDigits[i];
}
}
System.out.println("\n\npl: " + pl);
The issue is with if (count == i-1). Instead it should be if (count == i).Since you are checking from index 1, count will be 1(j=0) if no duplicate. Similarly, for i=2 count will be 2(j=1,0) if no duplicate. And same for the rest.

Why does java not print inside nested for loops inside a if else statement and appears as terminated?

So, I'm writing a program that returns pyramids when you give a word as an input
for instance:
"Enter a word: "
Hello
Justification (L=left, R=Right)?
L
would print
H
ee
lll
llll
oooo
import java.util.Scanner;
public class Justification{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter a word: ");
String word=in.nextLine();
System.out.println("Justification (L=left, R=Right)?");
String Justification=in.nextLine();
if(Justification.equalsIgnoreCase("l")){
for (int i = 0; i < word.length(); i++) {
for (int j = 1; j <= i; j++) {
System.out.print(word.substring(i,i));
}
System.out.println();
}
}else if(Justification.equalsIgnoreCase("r")){
for (int i = word.length()-1; i >= 0; i--) {
for (int s = 0; s < i; s++) {
System.out.print(" ");
}
for (int j = word.length()-1; j >= i; j--) {
System.out.println(word.substring(i,i));
}
System.out.println("");
}
}else System.out.println("Bad input");
}}
You are using substring(begin,end) incorrectly. The character at the begin index is included while the character at the end index is not.
If the word is hello, and you call substring(2,4), it would be ll
String str = "hello".substring(2,4); //str is "ll"
One way to check if substring is used correctly is that endIndex-beginIndex=length of substring. In this case, 4-2=2, so the substring should contain 2 characters, which it does.
An easier way to print out the ith character is to use charAt(i) instead of substring(i,i+1);
System.out.println("hello".substring(0,1)); //prints h
System.out.println("hello".charAt(0)); //also prints h

Java program to find the letter that appears in the most words?

I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3

Word count java

So my code is supposed to return the amount of words (words being lengths of letters) and it works except for when i enter anything 0 or less can some pplease help spot the error??
Edited Code:
public class WordCount {
public static int countWords(String original, int minLength){
String[] s1 = original.split("\\s+");
for(int i = 0; i < s1.length; i++){
s1[i] = s1[i].replaceAll("^\\W]", "");
}
int count = 0;
for(int i = 0; i < s1.length; i++){
String str = s1[i];
int len = 0;
for(int x = 0; x < str.length(); x++){
char c = str.charAt(x);
if(Character.isLetter(c) == true){
len ++;
}
}
if(len >= minLength){
count ++;
}
}
return count;
}
public static void main(String[] args){
System.out.println("enter string: ");
String s = IO.readString();
System.out.println("min length: ");
int m = IO.readInt();
System.out.println(countWords(s, m));
}
}
I would apply a solution that uses a regular expression to process the text.
I prepared a sketch of code, which can be summarized as follows:
String[] words = myString.replaceAll("[^a-zA-Z ]", " ").split("\\s+");
What this code does is to:
replace whatever is not a letter (since you said just letters) with a space
split the results on the spaces
The resulting array words contains all the words (i.e., sequences of letters) which were contained in the original string.
A full example can be found here. In this example I just print the words as a list. In case you want just the count of words, you just have to return the count of elements in the array.
Try this :
String s = original.replaceAll("[\\W]", " ").replaceAll("[\\s]+", " ");
because you have to replace spaces more than 1 here as well.

Find the word with the greatest numbers of repeated letters

For this challenge I need to find the word with the greatest numbers of repeated letters. For example, if I enter Hello world! the output should be Hello as it contains 2 characters of l, or No words and it should be -1.
I broke down the problem into:
1) Broke a sentence into the array of words
2) Went through each word in a loop
3) Went through each charcater in a loop
I'm stuck in how I should return if a word contains more letters than any other.
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter any sentence or word combination: ");
String myString = kbd.nextLine();
String result = "";
int count = 0;
String[] words = myString.split("\\s+");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length(); j++) {
for(int k = 1; k < words[i].length(); k++) {
char temp = words[i].charAt(k);
if(temp == words[i].charAt(k-1)) {
count++;
}
}
}
}
}
You almost did it and I suppose you're looking into something like this:
static int mostFreqCharCount(final String word) {
final int chars[] = new int[256];
int max = 0;
for (final char c : word.toCharArray()) {
chars[c]++;
if (chars[c] > chars[max]) // find most repetitive symbol in word
max = c;
}
return chars[max];
}
public static void main(final String[] args) {
System.out.println("Enter any sentence or word combination: ");
final Scanner kbd = new Scanner(System.in);
final String myString = kbd.nextLine();
kbd.close();
int maxC = 0;
String result = "";
final String[] words = myString.split("\\s+");
for (final String word : words) {
final int c = mostFreqCharCount(word);
if (c > maxC) {
maxC = c;
result = word;
}
}
if (maxC > 1) // any word has at least 1 symbol, so we should return only 2+
System.out.println(result);
}
the main idea - calculate number of most frequent symbol for each word and store only maximal one in variables maxC and result
You'll want to create an array of length = words.length, and store the highest value for each word in its relative index:
int counts[] = new int[words.length];
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length(); j++){
count = 0
for(int k = k+1; k < words[i].length(); k++){
if(words[i].charAt(j) == words[i].charAt(k)){
count++;
}
if(counts[i] < count)
counts[i] = count;
}
}
Then just scan through the array for the highest value, n, and return words[n]
If you just need the ONE word with the greatest count, you only need three variables, one for currentBestWord, one for currentLargestCount, and one to keep the count of characters in a word.
int currentLargestCount=0;
String currentBestWord="";
HashMap<String,Integer> characterCount=new HashMap<String,Integer>();
String[] words=myString.split("\\s+");
for(int i=0;i<words.length;i++){
String w=words[i];
characterCount=new HashMap<String,Integer>();
for(int j=0;j<w.length();j++){
String character=w.charAt(j).toString();
if(characterCount.containsKey(character)){
characterCount.put(character,characterCount.get(character)+1);
}else{
characterCount.put(character,1);
}
}
// Now get the largest count of this word
Iterator ir=characterCount.ValueSet().iterator();
int thiscount=0;
while(ir.hasNext()){
int thischaractercount=ir.next();
if(thiscount<thischaractercount) thiscount=thischaractercount;
}
if(thiscount>currentLargestCount){
currentLargestCount=thiscount;
currentBestWord=w;
}
}

Categories