I'm trying to find the smallest word in a user entered string. This is what I have so far:
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String myText = sc.next();
String[] myWords = myText.split(" ");
int shortestLength,shortestLocation;
shortestLength=(myWords[0]).length();
shortestLocation=0;
for (int i=1;i<myWords.length;i++) {
if ((myWords[i]).length() < shortestLength) {
shortestLength=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}
If I entered "SMALLEST WORD SHOULD BE A", the output should be A but it just gives me the first word of the string. Any ideas?
Your algorithm is fine, but instead of using next():
String myText = sc.next();
Which will only read a single token, i.e., the first word, use nextLine(), which will read the entire line:
String myText = sc.nextLine();
To take the full string you have to use the method
sc.nextLine();
thus it will take the complete string.
Related
Trying to split out a string and output the penultimate word inputted by the user, but the .split() only seems to be outputting a single string into the array so its not working?
import java.util.*;
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.next();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
System.out.println("Penultimate word " + words[words.length - 2]);
}
}
Problem is not with the split method, rather you should use nextLine instead of next:
String sentence = sc.nextLine();
The answer by #Aomine should resolve your problem. If you really wanted to use Scanner#next() directly, then you could also try setting the scanner's delimiter to be newline:
Scanner sc = new Scanner (System.in);
sc.useDelimiter(Pattern.compile("\\r?\\n"));
Then, calling Scanner#next() should default to returning the next full line.
You can use the whitespace regex
str = "Hello spilt me";
String[] splited = str.split("\\s+");
The split is working correctly. Reading of information from console is correct. Below changes should work.
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.nextLine();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
for (String currentWord : words ) {
System.out.println("The current word is" + currentWord);
}
}}
So basically what I need help I need help doing is removing a word from a sting. I dont know how to use array, char and such just for those who refer me to that.
Output Ex:
Enter a sentence: I really like Jolly Ranchers.
Enter a string: really
I like Jolly Ranchers.
I just need to remove every occurrence of the string from the sentence essentially. Thanks for help in advance!
(Not looking for a handout, perhaps pseudocode or another example.)
Use replaceAll function,
this function gets two params
regex - the string you want to replace
substr- the string to replace it with
example:
newString = str1.replaceAll(regex, substr);
newString is the edited string
str1 is the string you wish to edit
String.replaceAll works for that
package se.samples;
import java.util.Scanner;
public class WordRemover {
static final String welcomeMessage = "Enter a sentence: ",
secondMessage = "Enter a string: ",
resultMessage = "";
static String replace(String source, String that){
return source.replaceAll(that, "");
}
public static void main(String[] args) throws Exception {
System.out.print(welcomeMessage);
try(Scanner s = new Scanner(System.in)){
String input = s.nextLine();
System.out.print(secondMessage);
System.out.println(resultMessage + replace(input, s.nextLine()));
}
}
}
You can go this way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
String res ="";
for(String words : sentence.split(" ")){
if(!words.equalsIgnoreCase(word)){ //or words!=word if you want to NOT ignore the case
res+=words+" ";
}
}
return res;
}
public static void main(String[] args) {
System.out.println(remove());
}
It looks every word, and keep only the ones who are not equals to the word you enter
Or a more with a more shorter way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
return sentence.replaceAll(word,"");
}
Please try this
String[] s = originalString.split(" ");
String wordToRemove = StandardInput;
String finalString ="";
for(String word : s){
if(!word.equals(wordToRemove )){
System.out.Print(word);
finalString += word+" ";
}
}
I believe strings have a replace method so try something like str.replace("really", "") or replaceEach if there will be more than one. I suggest looking at the Java API for more functions.
I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The children are playing with their toys because they love it.
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String a = input.nextLine();
String b = input.nextLine();
String z[] = b.split(" ");
int number=0;
for (int i =0; i<z.length; i++){
if (z[i].contains(a))number++;
}
System.out.println(number);
I won't give you too much code, but here are the main talking points:
You need a way to read the input in. This can be accomplished with a Scanner - it's either from STDIN or a file.
You need a way to break up each word in the sentence. String#split will help you with that.
You need a way to ignore the casing of each sentence - toLowerCase() works well here.
You need to loop over each word in one sentence, as well as each occurrence in the other sentence. Consider that String.split produces a String[], and you can iterate over that with any standard for loop.
You need a way to see is a string is contained in another string. String#contains will help - although you want to be very careful on which side you're asking contains a string. For example:
// This will print true
System.out.println("The world".toLowerCase().contains("the"));
// This will print false
System.out.println("the".contains("The world".toLowerCase()));
Try this :
import java.util.Scanner;
public class Occurence {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine();
String str2 = input.nextLine();
int count = 0;
String word[] = str1.split(" ");
for (int i = 0; i < word.length; i++) {
if (word[i].toLowerCase().contains(str2.toLowerCase())) {
count++;
}
}
System.out.println("Occurence = " + count);
}
}
I want to be able to output the letter size of each word. So far my code only outputs the letter size of the first word. How do I get it to output the rest of the words?
import java.util.*;
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String words = sc.next();
String[] letters = words.split(" ");
for (String str1 : letters) {
System.out.println(str1.length() );
}
}
}
It's just because next returns only the first word (or also called the first 'token'):
String words = sc.next();
To read the entire line, use nextLine:
String words = sc.nextLine();
What you are doing should work then.
The other thing you can do is go ahead and use next all the way (instead of a split) because Scanner already searches for tokens using whitespace by default:
while(sc.hasNext()) {
System.out.println(sc.next().length());
}
Using sc.next() will only let the scanner take in the first word.
String words = sc.nextLine();
Iterate over all of the scanner values:
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String word = sc.next();
System.out.println(word.length() );
}
}
}