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.
Related
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
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(" ");
Here is SS of the whole question. http://prntscr.com/1dkn2e
it should work with any sentence not just the one given in the example
I know it has to do something with strings. Our professor has gone over with these string methods
http://prntscr.com/1dknco
This is only a basic java class so don't use any complicated stuff
here is what I have, don't know what to do after this
any help would be appreciated.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
}
}
You can use public String[] split(String regex):
splitted = sentence.split("\\s+");
splitted[0] Is the first word.
splitted[splitted.length - 1] Is the last word.
Since your'e not allowed to use String#split, you can do this trick:
myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord;
By doing this, you'll have a substring which contains the sentence without the last word. (For extracting the first word, you can use String#indexOf.
firstWord is the first word you extracted before (I'll not solve the whole problem for you, try to do it by yourself, it should be easy now)
Well as it seem your looking for very simple string arithmetic.
So that's the simplest i could do:
// get the index of the start of the second word
int index = line.indexOf (' ');
// get the first char of the second word
char c = line.charAt(index+1);
/* this is a bit ugly, yet necessary in order to convert the
* first char to upper case */
String start = String.valueOf(c).toUpperCase();
// adding the rest of the sentence
start += line.substring (index+2);
// adding space to this string because we cut it
start += " ";
// getting the first word of the setence
String end = line.substring (0 , index);
// print the string
System.out.println(start + end);
try this
String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);
Here is Another way you can do this.
UPDATED: Without Loops
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
int spacePosition = sentence.indexOf(" ");
String firstString = sentence.substring(0, spacePosition).trim();
String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
String firstChar = restOfSentence.substring(0, 1);
firstChar = firstChar.toUpperCase();
restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
System.out.println(restOfSentence + " " + firstString);
keyboard.close();
I need to get a number of words from user, and then output a final word which is formed by the concatenation of the last letters of the words that the user has input.
Here is the code. But how do I bring these letters from the loop and concatenate them?
import java.util.Scanner;
public class newWord {
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
System.out.println(str2);
}
}
}
Hints only ... since this is obviously a learning exercise of some kind.
But how do I bring these letters from the loop and concatenate them?
You don't. You concatenate them within the loop.
String concatenation can be done using the String + operator or StringBuilder.
The rest is up to you. (Please ignore the dingbats who posted complete solutions and work it out for yourself. It will do you good!)
You can use StringBuilder class to concatenate latest characters in strings with append method.
I believe (correct me if I'm wrong) you are asking to take the last letter of each word and make that into one final word. All you need to do is take each of the final letters and add them to a String to hold them all. After the entire for loop, the variable appended should be your requested word.
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
String appended = ""; // Added this
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
appended +=str2; // Added this
System.out.println(str2);
}
}
Just you miss things to keep final value in a place and finally print
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
StringBuffer sb = new StringBuffer();
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
sb.append(str2);
}
System.out.println(sb.toString());
}
go through StringBuilder and StringBuffer classes you will get your answer..
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.