Dictionary input file and string manipulation - java

I am writing a program that searches a file imported for a string of characters and length user enters. For example,
"Enter the possible letters in your word: "
Keyboard scans "aeppr"
"Enter the number of letters in your target words:"
"5"
and then proceeds to search my dictionary file and ultimately prints:
1 paper
I was wondering if you can use indexOf or any other methods or classes to display this result. As of now my code only displays words that match the searched letters and length exactly. Any help or advice would be greatly appreciated.
String input;
String altInput;
Scanner inFile = new Scanner(new File("words.txt"));
Scanner scanner = new Scanner(System.in);
String lettersBeingTested;
int numberOfLetters;
System.out.println("Enter the possible letters in your word: ");
lettersBeingTested = scanner.next();
System.out.println("Enter the number of letters in your target words: ");
numberOfLetters = scanner.nextInt();
int count = 0;
while (inFile.hasNext()) {
input = inFile.next();
altInput = "";
for (int i = 0; i < input.length(); i++) {
altInput = altInput + input.charAt(i);
if (input.contains(lettersBeingTested) && altInput.length() == numberOfLetters) {
count++;
System.out.println(count + " " + altInput);
}
}
}
System.out.println("End of list: " + count + " words found");
inFile.close();
}

public static void main(String[] args) throws FileNotFoundException {
findWords(new File("words.txt"));
}
public static void findWords(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the possible letters in your word: ");
String lettersBeingTested = scan.next();
System.out.println("Enter the number of letters in your target words: ");
int numberOfLetters = scan.nextInt();
int[] requiredHistogram = histogram(lettersBeingTested, new int[26]);
Predicate<int[]> predicate = wordHistogram -> {
for (int i = 0; i < requiredHistogram.length; i++)
if (requiredHistogram[i] > 0 && wordHistogram[i] < requiredHistogram[i])
return false;
return true;
};
Set<String> words = findWords(file, predicate, numberOfLetters);
int i = 1;
for (String word : words)
System.out.println(i + " " + word);
System.out.println("End of list: " + words.size() + " words found");
}
}
private static int[] histogram(String str, int[] histogram) {
Arrays.fill(histogram, 0);
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
histogram[str.charAt(i) - 'a']++;
return histogram;
}
private static Set<String> findWords(File file, Predicate<int[]> predicate, int numberOfLetters) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
Set<String> words = new LinkedHashSet<>();
int[] histogram = new int[26];
while (scan.hasNext()) {
String word = scan.next().toLowerCase();
if (word.length() == numberOfLetters && predicate.test(histogram(word, histogram)))
words.add(word);
}
return words;
}
}
This look a bit complicated using histogramm. I think that if lettersBeingTested = "aa", then you're looking for words with at lest 2 'a' in it. Threfore, you have to build a histogram and compare symbol appearance number in the current words and in example one.
P.S.
altInput = altInput + input.charAt(i);
String concatenation within loop flows bad performance. Do look at StringBuilder isntead.

Related

Want to print my stored names in array by JoptionPane, JAVA

public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}

How do I fix compiler errors in this program that counts characters, newlines, words of user input and returns them as an array

I am trying to write a program Count.java that counts the characters, newlines, and words in a string input by the user with a return value that is an array of the three counts.
I've written a program that is supposed to store a string entered by the user from the main method as the variable text in the method public static int[] analyze(String text) and, then, analyze it with the three integer count variables wordCount, charCount, and lineCount.
public class Count {
public static void main(String[] args) {
System.out.print("Please enter a string: ");
System.out.println(arr);
System.out.println("Total number of words: " + arr[0]);
System.out.println("Total number of characters: " + arr[1]);
System.out.println("Total number of newlines: " + arr[2]);
}
public static int[] analyze(String text) {
Scanner in = new Scanner(System.in);
String text = in.nextLine();
int wordCount = 0;
int charCount = 0;
int lineCount = 1;
int[] arr;
arr = new arr[] {wordCount, charCount, lineCount};
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' && text.charAt(i + 1) != ' ') {
wordCount++;
}
if (text.charAt(i) != ' ') {
charCount++;
}
}
if (text.charAt(i) == text.charAt(i)) {
lineCount++;
}
return arr;
}
}
I want it to output the number of characters, newlines, and words of the user's input string. However, when I try to run it, the compiler doesn't recognize my string variable text and array arr. Any suggestion for how I might fix this?
Jess,
There is my solution. Also I would suggest you to learn more java core and remember to try to google questions before you ask. Good luck in your journey :)
public class Count {
public static void main(String[] args) {
System.out.print("Please enter a string: ");
Scanner in = new Scanner(System.in);
String text = in.nextLine();
int arr[] = analyze(text);
System.out.println(arr);
System.out.println("Total number of words: " + arr[0]);
System.out.println("Total number of characters: " + arr[1]);
System.out.println("Total number of newlines: " + arr[2]);
}
public static int[] analyze(String text) {
int[] arr = new int[3];
// count lines
String[] lines = text.split("\r\n|\r|\n"); // taken from https://stackoverflow.com/questions/454908/split-java-string-by-new-line
arr[2] = lines.length;
// count number of words
arr[0] = countWords(text);
// count number of characters
arr[1] = counteCharacters(text);
return arr;
}
static final int OUT = 0;
static final int IN = 1;
static int countWords(String str) // taken from https://www.geeksforgeeks.org/count-words-in-a-given-string/
{
int state = OUT;
int wc = 0;
int i = 0;
while (i < str.length()) {
if (str.charAt(i) == ' ' || str.charAt(i) == '\n'
|| str.charAt(i) == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++wc;
}
++i;
}
return wc;
}
static int count = 0; // taken from https://www.javatpoint.com/java-program-to-count-the-total-number-of-characters-in-a-string
static int counteCharacters(String text) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != ' ')
count++;
}
return count;
}
}
I think you should analyse input data on new string available, because not to store it in one bit String object. Another note is to use Data object instead of an array; this is more intuitive:
public class Count {
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Please enter a string (empty line to stop): ");
Data data = analyze(scan);
System.out.println("Total number of words: " + data.totalWords);
System.out.println("Total number of characters: " + data.totalCharacters);
System.out.println("Total number of newlines: " + data.totalNewLines);
}
}
public static Data analyze(Scanner scan) {
Data data = new Data();
while (true) {
String line = scan.nextLine();
if (line.isEmpty())
break;
else {
data.totalNewLines++;
for (int i = 0; i < line.length(); i++)
if (!Character.isWhitespace(line.charAt(i)))
data.totalCharacters++;
data.totalWords += line.split("\\s+").length;
}
}
if (data.totalNewLines > 0)
data.totalNewLines--;
return data;
}
private static final class Data {
private int totalCharacters;
private int totalNewLines;
private int totalWords;
}
}

How to count the occurrences of a letter in a String without duplication in printing?

Please run the code if possible
input: "wooooow"
output:
w:2
o:5
o:5
o:5
o:5
o:5
w:2
I want the results to be : w:2 o:5
I have tried several ifs and loops to make it happen but I can't is there a syntax for it? or anything
import java.util.Scanner;
public class test {
public static void main( String[] args ){
String sWord= new String();
int nCtr,nCtr2,nTemp=0,n,n1=0,n2=0,n3=0;
char cTemp=' ',cTemp2=' ';
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
n = sWord.length();
char[] cArray = new char[n];
cArray = sWord.toCharArray();
for(int ctr=cArray.length;ctr>0;ctr--){
for(nCtr=0;nCtr<cArray.length;nCtr++){
if(cArray[nCtr]==sWord.charAt(n1)){
nTemp++;
}
}//for
cTemp = cArray[n2];
for(nCtr2=0;nCtr2<n;nCtr2++){
if(sWord.charAt(nCtr2)=='$'){
n3++;
}
}//for
System.out.println("# of occurence of " + cTemp + " is " + nTemp);
n1++;
n2++;
nTemp=0;
}//for minus
}//
}//class
You could try something like this:
import java.util.HashMap;
import java.util.Scanner;
public class test {
public static void main( String[] args ){
String sWord= new String();
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
HashMap<Character, Integer> charCount = new HashMap<Character, Integer>();
for(Character c : sWord.toCharArray()) {
if(charCount.containsKey(c)) {
charCount.put(c, charCount.get(c)+1);
} else {
charCount.put(c, 1);
}
}
for(Character key : charCount.keySet()) {
System.out.print(key + ":" + charCount.get(key) + " ");
}
}
}
This will print the following lines:
Enter a Word
wooooow
w:2 o:5
Should work for Uppercase, Lowercase, Numbers, ... everything you can save in a String.
edit:
Without using a HashMap:
public static void main( String[] args ){
String sWord= new String();
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
int[] cArr = new int[1024];
for(char c : sWord.toCharArray()) {
if((int) c <= cArr.length) {
cArr[(int) c]++;
}
}
for(int x = 0; x < cArr.length; x++) {
if(cArr[x] > 0) {
System.out.print((char) x + ":" + cArr[x]);
}
}
}
This works because you can cast a char to an integer and use it as an index for the array. Also you can do this reverse integer -> char.
This will work for the first 1024 Chars in your Charset. Normaly theese are all uppercase, lowercase, numbers and special characters.
This answer works only for lowercase input. For uppercase as well, use an array of size 46.
You will have to keep track of the occurrences yourself by creating a new array or some other data structure. Also, I dont think that your loops are very efficient.
import java.util.Scanner;
public class Temp {
public static void main( String[] args ){
String sWord= new String();
int nCtr,nCtr2,nTemp=0,n,n1=0,n2=0,n3=0;
char cTemp=' ',cTemp2=' ';
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
n = sWord.length();
char[] cArray = new char[n];
cArray = sWord.toCharArray();
int[] countsOfChars = new int[26];
for(int ctr=cArray.length;ctr>0;ctr--){
for(nCtr=0;nCtr<cArray.length;nCtr++){
if(cArray[nCtr]==sWord.charAt(n1)){
nTemp++;
}
}//for
cTemp = cArray[n2];
for(nCtr2=0;nCtr2<n;nCtr2++){
if(sWord.charAt(nCtr2)=='$'){
n3++;
}
}//for
// System.out.println("# of occurence of " + cTemp + " is " + nTemp);
countsOfChars[cTemp - 'a'] = nTemp;
n1++;
n2++;
nTemp=0;
}//for minus
for(int i=0; i<26; i++){
if(countsOfChars[i] != 0) {
System.out.println("# of occurence of " + (char)('a'+i) + " is " + countsOfChars[i]);
}
}
}//
}//class
You can try something like this
string str = "wooooow";
Dictionary<char, int> table = new Dictionary<char, int>();
foreach (char ch in str.ToCharArray())
{
int count = 0;
if (table.TryGetValue(ch, out count))
{
table[ch] = count + 1;
}
else
{
table.Add(ch, 1);
}
}
foreach (var item in table)
{
Console.Write(item.Key + ":" + item.Value+" ");
}

Palindrome checker - What am i doing wrong?

I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}
If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}
You should have done is
public static void main(String[] args) {
String Palin, input, Rinput = "";
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
for (int counter = str.length()-1; counter >= 0; counter--) {
Rinput = Rinput + str.charAt(counter);
}
if (Rinput.equalsIgnoreCase(str)) {
Palin = str;
System.out.println("Palin:" + Palin);
}
Rinput="";
}
}
I don't know if you are aware but StringBuilder has a reverse method to it. Which can be used like this :
public static void main(String[] args) {
String input;
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
if (new StringBuilder(str).reverse().toString().equalsIgnoreCase(str)) {
System.out.println("Palin:" + str);
}
}
}

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Categories