String split method java - java

I'm having a bit of difficulty getting my code to work. One of my assignments requires me to use this data from an external file (basically a passage/poem):
Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful
We are trying to find the total number of words, the number of words that have only three letters, and the percentage of occurrence of the three words. I think I can handle the assignment, but something went wrong in my code while I was working it out:
import java.io.*;
import java.util.*;
public class Prog739h
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\Java programs\\Prog739h\\Prog739h.in"));
int totalWords = 0;
while(kbReader.hasNextLine())
{
String data = kbReader.nextLine();
String[] words = data.split(" ");
totalWords+=words.length();
System.out.println(totalWords);
}
}
}
When I tried to compile to test the code at the moment to see if everything I had done was working properly, I was given an error that said it can't find symbol method length(). I checked my line with the "totalWords+=words.length()", but I don't know what I can do to fix the problem. Could someone please explain to me why this happened and provide some direction on how to fix this error? Thanks!

The answer is that the length of an array is given by the length field, not the length method. In other words, change
totalWords+=words.length();
to
totalWords+=words.length;

length is a public field on an Array object, the code is attempting to invoke it as a method using ()
Remove the () after length:
totalWords+=words.length

length is a property of array, access it without ()

please change:
totalWords+=words.length();
to
totalWords+=words.length;

Array properties shouldn't contain parenthesis
totalWords += words.length;
^

Related

String Name; Method 1: Atleast 2 words, max 4 words, no special signs and only letters

I've been searching around and havn't quite found my answer.
At this moment me and along with my group have created a few classes resembling a Bank with Customer and Account and so on.
I've been struggling lately with trying to improve and secure our code by making our variable called "name" only respond to certain inputs.
In this case, I want to make it only possible for the person to enter name as such:
Atleast 2 words = (For the word part I've seen codes where you count towards the white space between but don't know yet what you do about the last word since there wont be a white space)
Max 4 words = ( Same thing here)
No special signs such as ,!%¤"#()=%/'¨. = ( for this, I've read something about "Matcher and pattern" )
Now I'm quite new to Java and I'm not asking for a code from someone, I'm asking for someone to point me in the right directions regarding codes, because alot of what i've seen like the Matcher and pattern are things that you import with downloading utils and stuff but I reckon that it's not needed and there should be a simpler more basic way as I'm not trying to get ahead of myself with copying codes just to get it done.
So yeah, the String "name" is used alot in our main class "Banklogic" where almost every method that adds something has the variable "name" in it, so it's quite important that I get this done.
I hope I was clear enough and any help would be appreciated! I'm gonna put the alarm for 3 hours before school to see what you guys have come up with so I can try and complete the code before our meeting! Thanks alot in advance :)
Since you asked for hints, you can use Regex to add such rules.
For Numbers only:
if(string.matches("[0-9\\W]")
//allow insertion of data else not
As for rules related Word Count:
string.split("\\W") will create an array separated by space character. You can count the number of elements in this array and allow/disallow input based on that.
As for no signs and only letters:
if(string.matches("[a-zA-Z\\W]")
// Allow Input else not
You can use Document Filter to implement these methods. Document filter will only allow text to be entered if you allow it to.
I hope this helped as a hint.
Also, note that \\W is for whitespaces. If you dont want to allow whitespaces, remove that char.
This is the most effective and simple way of doing the task.
EDIT:
This is a Class I wrote a little while ago to achieve such tasks. Just in case if you are interested....

Select multiple lines from text file

I am working on a program that will create a word cloud from words that are spoken by a candidate in the presidential debate. The way the text file is set up one person can speak for multiple lines and I want to take in all those lines so I can count the frequency of the words they spoke. There is also a list of stop words that will not be counted for the word cloud. Some examples of the stop words are: "is", "a", "the" and so on. So far I have been able to take in all the stop words and the entire transcript for the debate and remove the stop words from the transcript. Now I want to separate the transcript into what each candidate said and I'm having troubles with it since a person speaks for multiple lines. Some help would be greatly appreciated.
Code so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ResendizYonzon {
public static void main(String[] args) throws FileNotFoundException
{
readTextFile("democratic-debate2015Oct13.txt");
}
public static String readTextFile(String text) throws FileNotFoundException {
File f = new File(text);
Scanner out = new Scanner(f);
String word = "";
File f1 = new File("stopwords.txt");
Scanner out1 = new Scanner(f1);
ArrayList<String> stopWords = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
while (out1.hasNext()) {
stopWords.add(out1.next());
}
while (out.hasNext()) {
words.add(out.next());
}
words.removeAll(stopWords);
out.close();
out1.close();
return word;
}
}
Transcript snippet:
CLINTON: No. I think that, like most people that I know, I have a range of views, but they are rooted in my values and my experience. And I don't take a back seat to anyone when it comes to progressive experience and progressive commitment.
You know, when I left law school, my first job was with the Children's Defense Fund, and for all the years since, I have been focused on how we're going to un-stack the deck, and how we're gonna make it possible for more people to have the experience I had.
You know, to be able to come from a grandfather who was a factory worker, a father who was a small business person, and now asking the people of America to elect me president.
COOPER: Just for the record, are you a progressive, or are you a moderate?
CLINTON: I'm a progressive. But I'm a progressive who likes to get things done. And I know...
(APPLAUSE)
...how to find common ground, and I know how to stand my ground, and I have proved that in every position that I've had, even dealing with Republicans who never had a good word to say about me, honestly. But we found ways to work together on everything from...
COOPER: Secretary...
CLINTON: ...reforming foster care and adoption to the Children's Health Insurance Program, which insures...
COOPER: ...thank you...
CLINTON: ...8 million kids. So I have a long history of getting things done, rooted in the same values...
COOPER: ...Senator...
CLINTON: ...I've always had.
COOPER: Senator Sanders. A Gallup poll says half the country would not put a socialist in the White House. You call yourself a democratic socialist. How can any kind of socialist win a general election in the United States?
SANDERS: Well, we're gonna win because first, we're gonna explain what democratic socialism is.
And what democratic socialism is about is saying that it is immoral and wrong that the top one-tenth of 1 percent in this country own almost 90 percent - almost - own almost as much wealth as the bottom 90 percent. That it is wrong, today, in a rigged economy, that 57 percent of all new income is going to the top 1 percent.
That when you look around the world, you see every other major country providing health care to all people as a right, except the United States. You see every other major country saying to moms that, when you have a baby, we're not gonna separate you from your newborn baby, because we are going to have - we are gonna have medical and family paid leave, like every other country on Earth.
Those are some of the principles that I believe in, and I think we should look to countries like Denmark, like Sweden and Norway, and learn from what they have accomplished for their working people.
(APPLAUSE)
Based on your description of problem in the question as well as in your comment to the question, you want to concatenate all speech given by a user into one, so that when a user asks for speech of a speaker i.e. CLINTON you just give them the parts of speech of CLINTON.
That is easy to accomplish. Which? the colon (:) is your ticket to solving this issue. If you look at the input file, whenever there is a new speaker the line starts with speaker name followed by colon.
What you need to do is following list of actions:
Open the file
Read the file line by line
For each line check if the line contains colon (:) or not
If the line contains colon then you need to split the line using colon as seperator
Assuming that you don't have colons elsewhere, splitting the following line
COOPER: Just for the record, are you a progressive, or are you a moderate?
gives you the following tokens (assuming there are no colons elsewhere)
Token[0] = COOPER
Token[1] = Just for the record, are you a progressive, or are you a moderate?
Now that you got two tokens, check if you are in just started reading transcript file or already have speakers
If just started reading the file then you got your first speaker so add him and initialize the variables
If already have other speakers then add the previous speaker (if not added yet) and update his/her speech before reading the speech of the new (or revisited) speaker.
If you continue above steps, every time you come across a speaker, you update the speech for it and add it to the hash map until the end of the line is reached.
Below is the sample code that would do above and is fully commented to help you understand it.
//public static HashSet that stores your speakers.
public static Map<String, String> speakerSpeech = new HashMap<String, String>();
public static void main(String[] args) throws FileNotFoundException
{
readTextFile("C:\\test_java\\transcript.txt");
}
public static void readTextFile(String text) throws FileNotFoundException {
File f = new File(text);
String line;
BufferedReader br;
try {
//open input stream to the path passed as text
FileInputStream fstream = new FileInputStream(text);
//open buffered reader using the input stream
br = new BufferedReader(new InputStreamReader(fstream));
//String builder used to append speech and lines (String is immutable)
StringBuilder speech = new StringBuilder();
// currentSpeaker is used for history. when new speaker is found, we should know who was previous one
// so we save all the speech that so far we have read
String currentSpeaker = null;
// while loop keeps looping over file line by line and terminates when line == null
// that is when end of file is reached.
while((line=br.readLine()) != null) {
//if line contains : then it is a line having a speaker, based on structure of your input file
if(line.contains(":")) {
//split the line using colon as seperator gives us 2 values (speaker and sentence) based
//on structure of your file
String[] chunks = line.split(":");
//store the speaker name CLINTON that was chunks[0] because left most value to colon
//triming whitespace (leading and trailing if any)
String speakerName = chunks[0].trim();
//condition to check if we just started reading transcripts or already read some
if(currentSpeaker == null) {
//just started reading transcript file, this is the first speaker ever
// assign the speaker to currentSpeaker
currentSpeaker = speakerName;
//add the remainder of speech after colon : to the speech StringBuilder
speech.append(chunks[1]);
} else {
//else because currentSpeaker is not null, we already have read speakers before
//current speaker is old speaker and we are about to scan new speaker so
//condition to check if speaker is already added to out list of speakers
if(speakerSpeech.containsKey(currentSpeaker)) {
//yes speaker is already added in map, then get its previous speechs
String previousSpeech = speakerSpeech.get(currentSpeaker);
//re-add the speaker in map and but this time with updated speech
//concatenating previous speech with current speech
speakerSpeech.put(currentSpeaker, previousSpeech + " >>> " + speech.toString());
} else {
//no speaker is new, then add it to the map with its speech
speakerSpeech.put(currentSpeaker, speech.toString());
}
//after storing previous speaker in list, add current speaker for record
currentSpeaker = speakerName.trim();
//initialize speech variable with new speakers speech after : colon
speech = new StringBuilder(chunks[1]);
}
} else {
//this else is because line did not have colon : hence, its continuation of speech
// of current speaker, just append to the speech
speech.append(line);
}
}
//because last line == null and loop terminates, we have to add the last speaker's speech to
//the list manually.
if(speakerSpeech.containsKey(currentSpeaker)) {
String previousSpeech = speakerSpeech.get(currentSpeaker);
speakerSpeech.put(currentSpeaker, previousSpeech + " >>> " + speech.toString());
} else {
speakerSpeech.put(currentSpeaker, speech.toString());
}
System.out.println("No. of speakers: " + speakerSpeech.size());
} catch(Exception ex) {
//handle error
}
//all speakers with their speech one giant string.
System.out.println(speakerSpeech.toString());
}
Executing the above gives you the following output:
{COOPER= Just for the record, are you a progressive, or are you a moderate? >>> Secretary... >>> ...thank you... >>> ...Senator... >>> Senator Sanders. A Gallup poll says half the country would not put a socialist in the White House. You call yourself a democratic socialist. How can any kind of socialist win a general election in the United States?, SANDERS= Well, we're gonna win because first, we're gonna explain what democratic socialism is.And what democratic socialism is about is saying that it is immoral and wrong that the top one-tenth of 1 percent in this country own almost 90 percent - almost - own almost as much wealth as the bottom 90 percent. That it is wrong, today, in a rigged economy, that 57 percent of all new income is going to the top 1 percent.That when you look around the world, you see every other major country providing health care to all people as a right, except the United States. You see every other major country saying to moms that, when you have a baby, we're not gonna separate you from your newborn baby, because we are going to have - we are gonna have medical and family paid leave, like every other country on Earth.Those are some of the principles that I believe in, and I think we should look to countries like Denmark, like Sweden and Norway, and learn from what they have accomplished for their working people.(APPLAUSE), CLINTON= No. I think that, like most people that I know, I have a range of views, but they are rooted in my values and my experience. And I don't take a back seat to anyone when it comes to progressive experience and progressive commitment.You know, when I left law school, my first job was with the Children's Defense Fund, and for all the years since, I have been focused on how we're going to un-stack the deck, and how we're gonna make it possible for more people to have the experience I had.You know, to be able to come from a grandfather who was a factory worker, a father who was a small business person, and now asking the people of America to elect me president. >>> I'm a progressive. But I'm a progressive who likes to get things done. And I know...(APPLAUSE)...how to find common ground, and I know how to stand my ground, and I have proved that in every position that I've had, even dealing with Republicans who never had a good word to say about me, honestly. But we found ways to work together on everything from... >>> ...reforming foster care and adoption to the Children's Health Insurance Program, which insures... >>> ...8 million kids. So I have a long history of getting things done, rooted in the same values... >>> ...I've always had.}

Entering Data into jGrasp without using a GUI

My class got a Java programming project today in class and the program we are using is jGrasp, I know that I can handle the pieces of this project except for one aspect.
The project requires the user to enter data into the program (i.e. answer a question), but for this Semester we are not using GUIs so I can't create a GUI for the user to input the data or answer.
I'd like to know how could the user enter data into jGrasp without using a GUI?
Thanks for taking the time to read this post, and I'd greatly appreciate any help you could give me.
I hope I'm helpful :) it's funny that I want to know about the same thing in GUI & you want to know without it :D ....well i can solve your matter I believe :)
From the starting,
Example:
import java.util.*;
public class Assignment //class name
{
static Scanner stdIn = new Scanner(System.in);
public static void main(String[]args)
{
int A, B; //Intialize variables as normal
System.out.print("Enter a question you want to ask "); //Between the double quotes " " you type anything you want to type :)
A = stdIn.nextInt();
: //
: // complete your program
System.out.println("Add the statement for giving the result "+B); // "+B" for inserting the answer along with your result statement
}
}
Note: In the statements,
System.out.print();
System.out.println();
These statement work similarly.... just the difference is statement with "print" is displayed on the same line & Statement with "println" is displayed in next line....when you will try you will understand ...just for avoiding confusion why I have written so I'm mentioning it :)
I hope this helps...tczz :)

I am trying to find the specific character within a String Array. What must I end up using?

Below is the code.\ I imagine you use a for loop and then another but I cannot seem to make it work. I attempted research however most topics were too complex since I am a novice. I'm trying to find a way to get the fifth character out of each string within the variable. I'll use the information given to me so i can then solve the rest of my program. I have more to do
public static void main (String[]args)
{
String[] decoder = {"Nexa2f5", "Z52Bizlm" , "Diskapr" , "emkem9sD", "LaWYrUs", "dAStn78L", "mPTuriye", "aaeeiuUu", "IL8Ctmpn"};
int character = 4;
for(int i=0; i<=decoder.length-1; i++)
{
}
}
I am trying to get the third and fourth characters of the odd numbered Strings. I am trying to put the letters into an array and decode the message. I am also trying to print the 5th character of all other words. I'm having issues commenting right and I've tried to reply a couple times but no dice.
Within your for loop use the array indexing notation. For example, String current = decoder[0] results in current having the value Nexa2f5. Once you have the String Object (in my example, I named it current) you can use the charAt() method shown in the String class documentation to get the 4th and 5th characters. If you need more help than that, read my comments then update your code and ask another question.

Implementing the useDelimiter method

I have the following code, please keep in mind I'm just starting to learn a language and a such have been looking for fairly simple exercises. Coding etiquette and critics welcome.
import java.util.*;
import java.io.*;
public class Tron
{
public static void main(String[] args) throws Exception
{
int x,z,y = 0;
File Tron= new File("C:\\Java\\wordtest.txt");
Scanner word = new Scanner(Tron);
HashMap<String, Integer> Collection = new HashMap<String, Integer>();
//noticed that hasNextLine and hasNext both work.....why one over the other?
while (word.hasNext())
{
String s = word.next();
Collection.get(s);
if (Collection.containsKey(s))
{
Integer n = Collection.get(s);
n = n+1;
Collection.put(s,n);
//why does n++ and n+1 give you different results
}else
{
Collection.put(s,1);
}
}
System.out.println(Collection);
}
}
Without the use of useDelimiter() I get my desired output based on the file I have:
Far = 2, ran = 4, Frog = 2, Far = 7, fast = 1, etc...
Inserting the useDelimiter method as follows
Scanner word = new Scanner(Bible);
word.useDelimiter("\\p{Punct} \\p{Space}");
provides the following output as it appears in the text file shown below.
the the the the the
frog frog
ran
ran ran ran
fast, fast fast
far, far, far far far far far
Why such a difference in output if useDelimiter was supposed to account for punctuation new lines etc? Probably pretty simple but again first shot at a program. Thanks in advance for any advice.
With word.useDelimiter("\\p{Punct} \\p{Space}") you are actually telling the scanner to look for delimiters consisting of a punctuation character followed by a space followed by another whitespace character. You probably wanted to have one (and only one) of these instead, which would be achieved by something like
word.useDelimiter("\\p{Punct}|\\p{Space}");
or at least one of these, which would look like
word.useDelimiter("[\\p{Punct}\\p{Space}]+");
Update
#Andrzej nicely answered the questions in your code comments (which I forgot about), however he missed one little detail which I would like to expand / put straight here.
why does n++ and n+1 give you different results
This obviously relates to the line
n = n+1;
and my hunch is that the alternative you tried was
n = n++;
which indeed gives confusing results (namely the end result is that n is not incremented).
The reason is that n++ (the postfix increment operator by its canonical name) increments the value of n but the result of the expression is the original value of n! So the correct way to use it is simply
n++;
the result of which is equivalent to n = n+1.
Here is a thread with code example which hopefully helps you understand better how these operators work.
Péter is right about the regex, you're matching a very specific sequence rather than a class of characters.
I can answer the questions from your source comments:
noticed that hasNextLine and hasNext both work.....why one over the other?
The Scanner class is declared to implement Iterator<String> (so that it can be used in any situation where you want some arbitrary thing that provides Strings). As such, since the Iterator interface declares a hasNext method, the Scanner needs to implement this with the exact same signature. On the other hand, hasNextLine is a method that the Scanner implements on its own volition.
It's not entirely unusual for a class which implements an interface to declare both a "generically-named" interface method and a more domain-specific method, which both do the same thing. (For example, you might want to implement a game-playing client as an Iterator<GameCommand> - in which case you'd have to declare hasNext, but might want to have a method called isGameUnfinished which did exactly the same thing.)
That said, the two methods aren't identical. hasNext returns true if the scanner has another token to return, whereas hasNextLine returns true if the scanner has another line of input to return.
I expect that if you run the scanner over a file which doesn't end in a newline, and consume all but one of the tokens, then hasNext would return true while hasNextLine would return false. (If the file ends in a newline then both methods will behave the same - as there are more tokens if and only if not all lines have been consumed - but they're not technically the same.)
why does n++ and n+1 give you different results
This is quite straightforward.
n + 1 simply returns a value that is one greater than the current value of n. Whereas n++ sets n to be one greater, and then returns that value.
So if n was currently 4, then both options would return 5; the difference is that the value of n would still be 4 if you called n + 1 but it would be 5 if you called n++.
In general, it's wise to avoid using the ++ operator except in situations where it's used as boilerplate (such as in for loops over an index). Taking two or three extra characters, or even an extra line, to express your intent more clearly and unambiguously is such a small price that it's almost always worth doing.

Categories