Recently, I've been trying to build a program that does 4 things:
1) Enter a word from the keyboard.
2) Check the context of this word with the context of a string that contains the letters of the alphabet.
3) Compare the letters of the given word with the letters of the alphabet string and whenever there is match, it will return the position of that letter in the alphabet string +1. (ex. word='a' position=1 since 'a' is the first letter)
4) Get the total of all of these positions.(ex. word='abc' total=6)
Now let me show you what I've written in terms of code.
//Part 1 Entering word from keyboard
package IntroductionJava;
import java.util.Scanner;
public class Numerology
{
public static void main(String[] args)
{
int m=0,n=0,sum=0;
int j,k;
Scanner user_input=new Scanner(System.in);
String word;
System.out.print("Give a word: ");
word=user_input.next();
String word1 = "\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03bf\u03c0\u03c1\u03c3\u03c2\u03c4\u03c5\u03c6\u03c7\u03c8\u03c9";
//Part 2 check word
for(int i=0; i<word.length(); i++)
{
if(word.charAt(i)>=word1.charAt(0) && word.charAt(i)<=word1.charAt(word1.length()-1))
{
System.out.println("Your word '"+word+"' is valid.");
break;
}
else
{
System.out.println("Your word '"+word+"' is invalid.");
}
break;
//show System.out.print(word.charAt(i));
}
//Part 3 Compare letters
for(j=0; j<word.length(); j++)
{
for(k=0; k<word1.length(); k++)
{
if(word.charAt(j)==word1.charAt(k))//???
{
m=k+1;
}
}
}
}
Now, Part 1 and 2 are working fine.
My problem lies when I try to compare the letters of the word that I'm entering with the String of letters in unicode format(the letters in unicode format are from the Greek alphabet). I've tried many variations, I've also consulted some of the articles here but I couldn't find a solution.
To make things a bit more clear let's say that I'm entering the word: "hello". I want to check whether 'h' is inside the alphabet string, and if it is I want to get it's position as an integer which in our case it's the number '8' (position in the string +1) and so on.
And the last part of my program is to get all those numbers from the given word and get it's total ('hello'=8+5+12+12+20=57).
Thank you very much in advance.
How about this:
String alphabet = "abcdefgh";
String input = "abc";
int value = input.chars()
.map(alphabet::indexOf)
.map(i -> i + 1)
.sum()
System.out.println(value);
Related
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
In Java, I am supposed to make a word game where one is supposed to make letters with a given set of random letters. I have already wrote the code to find the letters (Variable is String Letters ), but I am having trouble checking if the word chosen by the player (String word), is actually created using the given letters? I have a txt file of all the English words in the English language, and this is what I am basing it off if it is a word. How do I do this? I am pretty sure it has something to do with checking the index, or using the built in command contains at.
I have already tried to search for this. However other questions used C-Language or Python. I have found 1 Java explanation, however I am new to coding and do not understand the code and variables they used.
This is an example of where I need help
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
Full method.
public static void getWord(String letters) {
int trys = 0;
int trysLeft = 5;
System.out.println("Input a word that you can make with those letters");
while (trys < 5) {
String word = getString(); //getString is a method where user can input a desired string
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
}
else if (Words.contains(word) == false) {
System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
else if (Words.contains(letters) == false) {
System.out.println("You can not make a word with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
}
}
You need to check the cointains for each letter. If you send a charSeq, example { 'a' , 'b', 'd' }, java will try to find if your string contains completely "abd"
One way to do it is to sort the letters in your letter list and your word and see if your word is contains in the available letters, like this:
public static void main(String args[]) {
String letters = sort("haat");
System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
There are many techniques that you could use to implement this class project.
Here is one:
Build a Map from the input letters. The key of the map should be a Character and the Value of the map should be the count of letters.
Build a Map from the word guess. Again, the key of the map should be a Character and the Value of the map should be the count of letters.
Compare the maps. If they are equal, then the word is constructed from exactly the letters in the input letters string.
I need to check if two strings are anagrams but I cant use arrays.sort ... I know that I have to use for loop but I do not know how to start so that the chararray would be sorted alphabetically. Please, help me.
import java.util.Scanner;
public class Assignement3{
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println( "Please, type the first word: ");
String word1=sc.nextLine();
System.out.println( "Please, type the second word: ");
String word2=sc.nextLine();
String word1lower=word1.toLowerCase().replace(" ","");
String word2lower=word2.toLowerCase().replace(" ","");
System.out.println("Your First word is: " + word1lower);
System.out.println("Your Second word is: " + word2lower);
char[] firstword=word1lower.toCharArray();
char[] secondword=word2lower.toCharArray();
}
}`
I think that providing code which determines whether two strings are meaningful or actual anagrams of each other would require doing a lookup in a dictionary. But if we define an anagram of a word as being some permutation of the existing characters in the original word, then we can check for this fairly easily.
In the code snippet below, I read the characters from the first word into a map, keeping counts of the occurrences of each letter. This map of characters represents everything which is available to form a potential anagram. By iterating over the second word and keeping track of each character consumed, we can tell if the second word be an anagram. The marker for failure would be trying to use a character which does not appear or which has been exhausted already. Otherwise, the second word is a potential anagram.
String word1lower = "hala babel";
String word2lower = "baha label";
char[] firstword = word1lower.toCharArray();
char[] secondword = word2lower.toCharArray();
Map<Character, Integer> m1 = new HashMap<>();
int count = 0;
for (char c : firstword) {
Integer cnt = m1.get(c);
m1.put(c, cnt == null ? 1 : cnt.intValue() + 1);
++count;
}
boolean isAnagram = true;
for (char c : secondword) {
Integer cnt = m1.get(c);
if (cnt == null || cnt.intValue() == 0) {
isAnagram = false;
break;
}
m1.put(c, cnt.intValue() - 1);
--count;
}
if (isAnagram && count == 0) {
System.out.println("Second word is a full anagram of the first word.");
}
else if (isAnagram) {
System.out.println("Second word is a partial anagram of the first word.");
}
else {
System.out.println("Second word is not an anagram of the first word.");
}
Again, I say potential anagram here because to check whether a random combination of characters corresponds to an actual English (or other language) word would require a dictionary. This is way past the scope of a single Stack Overflow question, but hopefully my answer gets you thinking in the right direction.
Demo here:
Rextester
trying to write a simple Java program that accepts a string and validates against two criteria.
If the word is shorter than 4 letter it asks the user to re enter a word till it is four letters..
Once that criteria is true it evaluates it against the letters. If the first letter of the four letter word is a D then it prints a silly message "The D was found" if not "No D found"
So far what i have working is validation for the four letters. It checks that it is four letters and if its not it keeps asking till it gets a four letter word.
After that when i enter the four letter word i cant get it to validate on the next if which checks if it is greater than 4 letters and then checks if it starts with a D or not.
import java.util.Scanner;
public class POD1
{
private static Scanner scan = new Scanner(System.in);
private static String word;
public static void main(String [] args)
{
System.out.println("Please enter a 4 Letter word");
word = scan.next();
if(word.length() <4)
{
System.out.println("Word is to short ");
System.out.println("Plese re-enter");
word = scan.next();
}
if(word.length() > 4)
{
if(word.charAt(1) == 'd')
{
System.out.println("Big d");
} else
if( word.charAt(1) !='d')
{
System.out.println("No big d");
}
}
}
}
UPDATE
The code now does go past 4 letter words but even if the word starts with a d it prints out no big d even though it starts with a d
You should be having the following to include 4 lettered words as well
if(word.length() >= 4)
You are scanning and taking the input until word.length() <4. So the loop breaks when the length is 4.
So, it doesn't enter the next if statement.
A better implementation would be to use the else clause
if(word.length() <4) {
System.out.println("Word is to short ");
System.out.println("Plese re-enter");
word = scan.next();
} else {
if(word.charAt(0) == 'D')
{
System.out.println("Big D");
} else
if( word.charAt(0) !='D')
{
System.out.println("No big D");
}
}
}
Also, you should be checking for 'D' and not 'd', if you are looking for "Big D".
Also, the index of the first character in a String is 0. So, you should be using word.charAt(0) == 'D', and not index 1 as you are using in your code right now. Index 1 will return the second character.
You check wether the word is shorter than 4 letters AND wether the word is longer than 4 letters.
There is absolutely nothing in your code that includes 4 letter words.
if(word.length() >= 4)
should be used.
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