I am trying to write a few methods for my homework assignment but I don't know what to do.
I've tried a bunch of things but none seemed to work.
First Question is how do i take a string I have and return it with no spaces. trim() only eliminates the first and last whitespace of the sentence(getNoSpaceString method).
Also I am trying to count the number of digit words my sentence has aka one is 1 digit word.
My code is below(digitWordCount method).
import java.util.*;
public class StringProcessor {
private String noSpaces;
private String input, noVowels;
private String noDigitWords;
private int numOfWords = 0, uppercaseLetters = 0,
numOfDigits = 0, digitWords = 0;
public StringProcessor()
{
input = "";
}
public StringProcessor(String s)
{
StringTokenizer str = new StringTokenizer(s);
numOfWords = str.countTokens();
for (int i = 0; i < s.length(); i++)
{
if (Character.isUpperCase(s.charAt(i)))
uppercaseLetters++;
}
for (int i = 0; i < s.length(); i++)
{
if (Character.isDigit(s.charAt(i)))
numOfDigits++;
}
if (str.nextToken().equalsIgnoreCase("one"))
digitWords++;
}
public void setString(String s)
{
input = s;
}
public String getString()
{
return input;
}
public int wordCount()
{
return numOfWords;
}
public int uppercaseCount()
{
return uppercaseLetters;
}
public int digitCount()
{
return numOfDigits;
}
public int digitWordCount()
{
return digitWords;
}
public String getNoSpaceString()
{
return noSpaces;
}
public String getNoVowelString()
{
return noVowels;
}
public String getNoDigitWordString()
{
return noDigitWords;
}
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
StringProcessor str = new StringProcessor(input);
System.out.println("\nwords: " + str.wordCount());
System.out.println("uppercase: " + str.uppercaseCount());
System.out.println("digits: " + str.digitCount());
System.out.println("digit words " + str.digitWordCount());
System.out.println("line with no spaces: ");
}
}
For your first question, try finding out how to replace " " which is a whitespace into "" which is nothing (there are also string functions for this in case you've seen this in your classes already)
For your second question it might help to know that a string is an array of characters, again, in case you have seen string functions already you should probably look into the documentation you've gotten around that (or google it)
I hope you don't mind me not giving you straight up answers, seeing as this is a homeworks assignment you should probably just find it yourself, I just thought i'd get you on the right track.
First Question is how do i take a string I have and return it with no spaces. trim() only eliminates the first and last whitespace of the sentence(getNoSpaceString method).
String input = " Hello World ";
You can achieve this by:
String input2 = input;
input2 = input.replaceAll(" ", "");
Take a look here for more information
Second question:
Also I am trying to count the number of digit words my sentence has aka one is 1 digit word.
If you're trying to count number of words, then:
int words = input.trim().split(" ").length;
System.out.println("number of words: " + words);
Here's how split works
Let me know it this isn't what you're looking for for 2nd question
If you care less about time complexity, you can just use a for loop to iterate the string passed in. make another string to hold what to return, say, call it toReturn. in the for loop, all you need to do is to determine if this character is a " ". Use .charAt(i) to do so. if it's not, just attach it to the toReturn. after the for loop, you will have what you want to return.
For the first one, although there is a way to do it using library methods, given that it's a homework assignment, you should probably be looping through the characters one by one and then adding them to a new "result" string if they meet the criteria (i.e. not a space).
For the second one, there is a library method which you can use to split the string on spaces, which will give you a list of the words. You should have also created a list of each of the 10 "digit" words. Then you can iterate over your list of input words and see if they match any of the digit words.
Related
I looking for a way to split my chunk of string every 10 words.
I am working with the below code.
My input will be a long string.
Ex: this is an example file that can be used as a reference for this program, i want this line to be split (newline) by every 10 words each.
private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {
String[] names = jTextArea13.getText().split("\\n");
var S = names.Split().ToList();
for (int k = 0; k < S.Count; k++) {
nam.add(S[k]);
if ((k%10)==0) {
nam.add("\r\n");
}
}
jTextArea14.setText(nam);
output:
this is an example file that can be used as
a reference for this program, i want this line to
be split (newline) by every 10 words each.
Any help is appreciated.
I am looking for a way to split my chunk of string every 10 words
A regex with a non-capturing group is a more concise way of achieving that:
str = str.replaceAll("((?:[^\\s]*\\s){9}[^\\s]*)\\s", "$1\n");
The 9 in the above example is just words-1, so if you want that to split every 20 words for instance, change it to 19.
That means your code could become:
jTextArea14.setText(jTextArea13.getText().replaceAll("((?:[^\\s]*\\s){9}[^\\s]*)\\s", "$1\n"));
To me, that's much more readable. Whether it's more readable in your case of course depends on whether users of your codebase are reasonably proficient in regex.
You can try this as well leveraging the java util
public static final String WHITESPACE = " ";
public static final String LINEBREAK = System.getProperty("line.separator");
public static String splitString(String text, int wordsPerLine)
{
final StringBuilder newText = new StringBuilder();
final StringTokenizer wordTokenizer = new StringTokenizer(text);
long wordCount = 1;
while (wordTokenizer.hasMoreTokens())
{
newText.append(wordTokenizer.nextToken());
if (wordTokenizer.hasMoreTokens())
{
if (wordCount++ % wordsPerLine == 0)
{
newText.append(LINEBREAK);
}
else
{
newText.append(WHITESPACE);
}
}
}
return newText.toString();
}
You were so close.
You were not appending your split words before setting it back into your text box. StringBuilder sb.append(S[k]) will add your split name to a buffer. sb.append(" ") will then add a space. Each line will be of 10 space separated names.
StringBuilder sb = new StringBuilder();
String[] names = jTextArea13.getText().split(" ");
for (int k = 0; k < S.length; k++) {
sb.append(S[k]).append(" ");
if (((k+1)%10)==0) {
sb.append("\r\n");
}
}
At last print it back to your jTextArea using:
jTextArea14.setText(sb.toString());
Just a side note, since sb is StringBuilder, you need to change it to string using toString nethod.
I am trying to find the shortest word from a string array, but I am removing special characters using reg ex with the code
public String[] setWordArray(String stringToBeAnaylsedForFrequency) {
stringToBeAnaylsedForFrequency = stringToBeAnaylsedForFrequency.replaceAll("\\d+", " ");
stringToBeAnaylsedForFrequency = stringToBeAnaylsedForFrequency.replaceAll("\\W", " ");
stringToBeAnaylsedForFrequency = stringToBeAnaylsedForFrequency.replaceAll("( )+ ", " ");
String[] wordArray = stringToBeAnaylsedForFrequency.split(" ");
return wordArray;
}
and this is the method for use
public String getShortestWordInStringGiven() {
int wordArrayLength = getStringArrayForGivenString().length;
String shortestWordInGivenString = getStringArrayForGivenString()[0];
for (int i = 1; i < wordArrayLength ; i++) {
if (getStringArrayForGivenString()[i].length() < shortestWordInGivenString.length()) {
shortestWordInGivenString = getStringArrayForGivenString()[i];
}
}
return shortestWordInGivenString;
}
when it works fine i input text like hello you, it would return you as the shortest character, but when i input "hello you" with a special character at the start it returns nothing.
Answering to your comments: When you have a space in the beginning, split will have one more element, an empty String, in the beginning. That one is the shortest element in the array (check for the array's length), but printing it reveals nothing that's visible. But, rest assured, the correct element is printed: it's ""
You might want to trim your String before the split operation
I am trying to make a program that should checks if the string that the program is currently looking at, contains the word ing in that specific order. I figured out to just split the string with spaces, so each word can be looked at individually. I am stuck on the if condition. The if condition determines if the word has ing in it. For the assignment I can only use one loop and two if statements. I cannot use the string methods tolower or upppercase. Also this what the output needs to look like: (for the output i have a test class that gives me strings to test out)
Words with ing:
Singing Dancing
if I do not find any words what have ing the output should like this
There are no words with ing
Here is my code till now:
public class EndsWith
{
public static void endsWithIng (String s)
{
String[] a = s.splits(" ");
for(int i = 0; i < a.length; i++)
{
// if()
System.out.print(a[i] + "");
}
}
}
I found the answer for my problem. I forgot to mention that the problem also required a specific print statement. My solution is similar but I made a new string and added any words that I found with ing to that new string. Also I used a counter to keep track if a word with ing is even found in the first place. If it is not than I printed after the loop no words with ing found.
public class EndsWith
{// start of cLASS
public static void endsWithIng (String s)
{// START of method
String ing="";
String compare="";
String [] a = s.split(" ");
//System.out.println("Words with ing: ");
int i;
int count=0;
for(i=0;i<a.length;i++)
{//start of for
compare=a[i];
if(compare.matches(".*[iI][nN][gG].*"))
{ //start of if
//System.out.print(compare + " ");
count++;
ing+=a[i] +" ";
}
}
if(count==0)
{
System.out.println("There are no words with ing");
}
else
{
System.out.println("Words with ing: ");
System.out.println(ing);
}
}
}
I think you are looking to split on one (or more) white-space characters. You can also use String.endsWith(String)1. Something like,
public static void endsWithIng(String s) {
String[] a = s.split("\\s+");
for (int i = 0; i < a.length; i++) {
if (a[i].toLowerCase().endsWith("ing")) {
System.out.print(a[i] + " ");
}
}
}
or you could use an enhanced for-each loop like2
public static void endsWithIng(String s) {
String[] a = s.split("\\s+");
for (String value : a) { // <-- for each value in array a
// This checks if the last three characters make the String "ing"
if ("ing".equalsIgnoreCase(value.substring(value.length() - 3))) {
System.out.print(value + " ");
}
}
}
To use a regular expression, beyond String.split(String), you can use String.matches(String) like
public static void endsWithIng(String s) {
String[] a = s.split("\\s+");
for (String value : a) { // <-- for each value in array a
// This test ignores case for iI nN gG
if (value.matches(".*[(i|I)(n|N)(g|G)]$")) {
System.out.println(value);
}
}
}
1You since added the stipulation that you cannot use toLowerCase. Next time, for better help faster, please give all the requirements when you ask the question.
2This example uses Yoda conditions.
I know I'm missing some things and that's what I really need help with. The code doesn't work in all cases and am looking for help improving/fixing it.
Assignment:
The code I have so far:
public String word(int num, String words)
{
int l = words.indexOf(" ");
int r = words.indexOf(" ", l+1);
for(int i = 3; i <= num; i++){
l = r;
r = words.indexOf(" ", l+1);
//if(i != num)
// l = r;
}
String theword = words.substring(l,r);
return theword;
}
}
As this is clearly homework, I will give you text only.
Your approach may work eventually, but it is laborious and overly complicated, so it's hard to debug and hard to get right.
make use of String's API by using the split() method
after splitting the sentence into an array of word Strings, return the element at num less one (array are indexed starting at zero
check the length of the array first, in case there are less words than num, and take whatever action you think is appropriate in that case
For part 2, a solution in a simple form may be:
create a new blank string for the result
iterate over the characters of the given string adding the character to the front of the result string
make use of String's toUpperCase() method
Since this is homework and you have showed some effort. This is how you can do part 1 of your question. This code is pretty evident.
1) I am returning null if number is greater than the number of words in string as we dont want user to enter 5 when there are only 2 words in a string
2) Splitting the string by space and basically returning the array with the number mentioned by user
There are more conditions which you must figure out such as telling the user to enter a number of the string length since it would not give him any result and taking input from Scanner instead of directy adding input in method.
public static String word(int num, String words)
{
String wordsArr[] = words.split(" ");
if(num <= 0 || num > wordsArr.length) return null;
return (wordsArr[num-1]);
}
the second part of your question must be attempted by you.
Well... not often you see people coming here with homework AND showing effort at the same time so bravo :).
This is example of how you can split the string and return the [x] element from that string
public class SO {
public static void main(String[] args) throws Exception {
int number = 3;
String word = "Hello this is sample code";
SO words = new SO();
words.returnWord(number, word);
}
private void returnWord(int number, String word) throws Exception {
String[] words = word.split("\\s+");
int numberOfWords = words.length;
if(numberOfWords >= number) {
System.out.println(words[number-1]);
} else {
throw new Exception("Not enought words!!!");
}
}
}
Yes it is a working example but do not just copy and paste that for your homework - as simple question from teacher - What is this doing, or how this works and your out :)! So understand the code, and try to modify it in a way that you are familiar what is doing what. Also its worth getting some Java book - and i recommend Head first Java by O'Really <- v.good beginner book!
if you have any questions please do ask!. Note that this answer is not 100% with what the textbook is asking for, so you can modify this code accordingly.
As of part 2. Well what Bohemian said will also do, but there is a lot quicker solution to this.
Look at StringBuilder(); there is a method on it that will be of your interest.
To convert String so all letter are upper case you can use .toUpperCase() method on this reversed string :)
You can try:
public class trial {
public static void main(String[] args)
{
System.out.println(specificword(0, "yours faithfully kyobe"));
System.out.println(reverseString("derrick"));}
public static String specificword(int number, String word){
//split by space
String [] parts = word.split("\\ ");
if(number <= parts.length){
return parts[number];
}
else{
return "null String";
}
}
public static String reverseString(String n){
String c ="";
for(int i = n.length()-1; i>=0; i--){
char m = n.charAt(i);
c = c + m;
}
String m = c.toUpperCase();
return m;
}
}
For the first problem, I'll give you two approaches (1. is recommended):
Use the String.split method to split the words up into an array of words, where each element is a word. Instead of one string containing all of the words, such as "hello my name is Michael", it will create an array of the words, like so [hello, my, name, is, Michael] and that way you can use the array to access the words. Very easy:
public static String word(int num, String words)
{
// split words string into array by the spaces
String[] wordArray = words.split(" "); // or = words.split("\\s+");
// if the number is within the range
if (num > 0 && num <= wordArray.length) {
return wordArray[num - 1]; // return the word from the word array
} else { // the number is not within the range of words
return null;
}
}
Only use this if you cannot use arrays! Loop through the word until you have found enough spaces to match the word you want to find:
public static String word(int num, String words)
{
for (int i = 0; i < words.length(); i++) { // every character in words
if (words.substring(i, i+1).equals(" ")) { // if word is a space
num = num - 1; // you've found the next word, so subtract 1 (number of words left is remaining)
}
if (num == 1) { // found all words
// return this word
int lastIndex = i+1;
while (lastIndex < words.length()) { // until end of words string
if (words.substring(lastIndex, lastIndex+1).equals(" ")) {
break;
}
lastIndex = lastIndex + 1; // not a space so keep moving along the word
}
/*
// or you could use this to find the last index:
int lastIndex = words.indexOf(" ", i + 1); // next space after i+1
if (lastIndex == -1) { // couldn't find another space
lastIndex = words.length(); // so just make it the last letter in words
}*/
if (words.substring(i, i+1).equals(" ")) { // not the first word
return words.substring(i+1, lastIndex);
} else {
return words.substring(i, lastIndex);
}
}
}
return null; // didn't find word
}
As for the second problem, just iterate backwards through the string and add each letter to a new string. You add each letter from the original string to a new string, but just back to front. And you can use String.toUpperCase() to convert the string to upper case. Something like this:
public static String reverse(String str) {
String reversedString = ""; // this will be the reversed string
// for every character started at the END of the string
for (int i = str.length() - 1; i > -1; i--) {
// add it to the reverse string
reversedString += str.substring(i, i+1);
}
return reversedString.toUpperCase(); // return it in upper case
}
So the code I have is for a homework assignment where the user inputs a sentence (string) and I need to search through the string and return the smallest word. However, there must be a number inputted at the first spot in the string. Ex: "4 WHAT IS THIS". Output should be "IS" and ignore the number. The only way I figured out how to ignore the number is to make the loop skip over the first spot where the number would be. It works by itself but whenever I put it into the rest of my program it stops working. Is there anyway to make this program cleaner?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Lexicographically smallest word
String TheSentence = sc.nextLine();
String[] myWords = TheSentence.split(" ");
int shortestLengths, shortestLocation;
shortestLengths = (myWords[1]).length();
shortestLocation = 1;
for (int i = 1; i < myWords.length; i++) {
if ((myWords[i]).length() < shortestLengths) {
shortestLengths = (myWords[i]).length();
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}
Inside your for loop (that should start at i = 0), add code like this:
try {
double value = Double.parseDouble(myWords[i]);
} catch (NumberFormatException e) {
// add the rest of your code here
}
The idea is that you try to transform your word to a number and if you fail, it means it's not a number, so you can use the length logic on the word.
The first thing you should do is to create the function you want to use instead of mixing the relevant code for the exercice with things like reading a line from the input stream.
You can test whether a character is a letter using Character.isLetter(char).
A good exercice is to build a solution using only that function and looking at each character separately (String.charAt(int) method) in a loop.
The solution is to remember where the currently shortest word starts and how long it is.
In practice, I would just use regexes like this:
public static String shortestWord(String sentence) {
String shortest = null;
Pattern word = Pattern.compile("\\w+");
Matcher m = word.matcher(sentence);
while (m.find()) {
String candidate = m.group();
if (shortest == null || shortest.length() > candidate.length())
shortest = candidate;
}
return shortest;
}
You could try using substring, e.g.
String result=inputString.substring(1)
'1' being the second letter in the string, substring returning every value save for the first.
The below basically just shortens up your code..other than that it doesn't change much. That being said..it would be much better to create all this in a method called shortestWord() or something. There is really no reason the code below shouldn't work though.
Revised Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] myWords = (sc.nextLine()).split(" ");
int shortestLocation = 1
for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
// already made shortestLocation = 1
if (myWords[i].length() < myWords[shortestLocation].length()) {
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}
Suggested Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] myWords = (sc.nextLine()).split(" ");
System.out.println("The shortest word is: " + shortestWord(myWords));
}
public static String shortestWord(String[] myWords) {
int shortestLocation = 1
for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
// already made shortestLocation = 1
if (myWords[i].length() < myWords[shortestLocation].length()) {
shortestLocation = i;
}
}
return myWords[shortestLocation];
}