Determining number of character in a string - java

Ok what I'm wanting to do is find out if the length of the word entered is divisible by two or not. If it is I want to take the middle two characters (say it was Game, I'd want 'am') and add it to another word.
import java.util.Scanner;
public class Assign33 {
public static void main(String[] args) {
System.out.println("Enter 3 words(Has to contain 4 letters)");
String word1;
String word2;
String word3;
Scanner in = new Scanner(System.in);
// Reads a single line word
// and stores into word variable
word1 = in.nextLine();
word2 = in.nextLine();
word3 = in.nextLine();
// gets each letter if the word has four letters
//this is the part I want to change
String sub0 = word1.substring(1,3)+word2.substring(1,3)+word3.substring( 1, 3 );
// Prints the new word
System.out.println("Can you pronounce: "+sub0);
}
}

If you want to find out the length of a string use .length().
That should help you figure out where the middle of the word is.

If your input can have more than one word then filter the first word from the
line.
word1 = word1.replaceAll("^\s*(\w+)\s*.*$","$1");
If your input would have only one word then trim it.
word1 = word1.trim();
Find the length.
int length1 = word1.length();

If I understand your question correctly, here is what you can do:
String myWord = "Game";
String trimmedWord = myWord.trim();
int lengthOfWord = trimmedWord.length();
boolean lengthIsDivisibleByTwo = lengthOfWord%2 == 0;
String middleSection = "";
if (lengthIsDivisibleByTwo) {
int middleLetterIndex = lengthOfWord/2;
middleSection = trimmedWord.substring(middleLetterIndex-1, middleLetterIndex+1);
}
Then the "middleSection" variable will hold your "am", or whatever the middle 2 letters are.

Related

How do I print a letter based on the index of the string?

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.

Loop expects an input, while it should've iterated through every word of previous input

Need to change every word, that starts with vowel to the longest one. Everything seems ok, however have faced with an unexpected behaviour from the loop, when I enter into it - scanner wants an input (7th line). Instead of asking for an input, it should iterate through every element (word) from the sentence I've set previously (2nd line). I do assume, that I've missed something.
Scanner sc = new Scanner(System.in);
String textToFormat = sc.nextLine();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(textToFormat);
while (sc.hasNext()) {
currentWord = sc.next();
if (currentWord.length() > longestWord.length()) {
longestWord = currentWord;
} else break;
}
By looking at your code, I see you are trying to find the longest string in a sentence inputted by user.
There is no need to input every word individually when you simply could input the entire line. Something like the following code could help you:
import java.util.Scanner;
public class Main {
public static String findLongestWord(String[] arr){
String longest = "";
for (String current : arr){
// If the current word is larger than the longest.
if(current.length() > longest.length()){
longest = current; // Then set longest word to current.
}
}
return longest;
}
public static void main(String[] args) {
// Get the sentence from the user.
System.out.println("Input a sentence: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
// Split sentence into words.
String[] arr = s.split("\\W+");
System.out.println("Longest word is " + findLongestWord(arr));
}
}
When run with input Find the longest word in this large sentence this outputs:
Input a sentence:
Find the longest word in this large sentence.
Longest word is sentence

how to add an additional method to get word count and first word of a string

I'm still fairly new to Java and understanding the basics of everything, we just started talking about methods.
I'm having a hard time implementing this new method.. without using arrays or vectors or anything in the sort..
Any help would be greatly appreciated!
public class ClosedLab07{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
String str = getInputString(keyboard);
int count = getWordCount(str);
System.out.println("Your string has " + (count+1) + " words in it.");
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(Scanner inScanner) {
String str = "";
while (str.equals("")){
System.out.print("Enter a string: ");
str = inScanner.nextLine();
if (str.equals("")){
System.out.println("ERROR - string must not be empty.");
System.out.println();
}
}
return str;
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
int i = 0;
int wordCount = 0;
while (i < input.length()){
char pos = input.charAt(i);
if (pos == ' '){
wordCount++;
}
i++;
}
return wordCount;
// Fill in the body
}
private static String getFirstWord(String input)
// THIS IS THE METHOD I'M WORKING ON
}
Add this line to your new method
return input.split("\\s")[0]; // split returns an array of all the words. you need just the first word

String Array for Java

I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.
How can I code this? Also, how do I display it with System.out.println();?
Okey so, here is my code so far:
import java.util.Scanner;
import java.util.StringTokenizer;
public class OddSentence {
public static void main(String[] args) {
String sentence, word, oddWord;
StringTokenizer st;
Scanner scan = new Scanner (System.in);
System.out.println("Enter sentence: ");
sentence = scan.nextLine();
sentence = sentence.substring(0, sentence.length()-1);
st = new StringTokenizer(sentence);
word = st.nextToken();
while(st.hasMoreTokens()) {
word = st.nextToken();
if(word.length() % 2 != 0)
}
System.out.println();
}
}
I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.
Based on what you've given alone, I would say use #split()
String example = "What is your deal?"
String[] spl = example.split(" ");
/*
args[0] = What
args[1] = is
args[2] = your
args[3] = deal?
*/
To display the array as a whole, use Arrays.toString(Array);
System.out.println(Arrays.toString(spl));
To read and split use String.split()
final String input = "What is your deal?";
final String[] words = input.split(" ");
To print them to e.g. command line, use a loop:
for (String s : words) {
System.out.println(s);
}
or when working with Java 8 use a Stream:
Stream.of(words).forEach(System.out::println);
I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.
String str = "This is a string";
String[] strArray = str.split(" "); //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
if((strArray[i].length() % 2) == 0) { //if there is an even number of characters in the string
System.out.println(strArray[i]); //print the string
}
}
Output:
This is string
If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)
This will give you just a as the output (the only word in the string with an odd number of characters).
Let input be your input string. Then:
String[] words = input.split(" ");

How to break the 4 words using substring method

I'm wanting to break up a sentence consisting of 4 words, into individual words. But, I'm not sure how to tell it to start from after the first space and stop and the next space in the sentence.
import java.util.Scanner;
public class arithmetic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in)
String sentence;
String word1, word2, word3, word4;
int p, p2;
System.out.print("Enter a sentence with 4 words:");
sentence = in.nextLine();
p = sentence.indexOf(" ");
word1 = sentence.substring(0,p)+(" ");
word2 = sentence.substring()(" ");
word3 = sentence.substring()+(" ");
word4 = sentence.substring()+(" ");
sentence = word1+word2+word3+word4;
System.out.println(sentence);
This sounds like a job for StringTokenizer!
words = new StringTokenizer(sentence).split("\\s");
Now you have an array of strings contained in words, and you can do whatever you want with them, like turn them into another sentence.
You could also use the String.split() method as follows:
String[] parts = sentence.split("\\s");
which yields exactly the same results as Chris approach.

Categories