I wrote a piece of code to look through a String named line with several lines(hence newline characters) in it. my code prints all locations of the string Context in the line. how do i modify the code to print the occurence
String Context = ("[020t");
int index =0;
int count = 0;
while((index = line.indexOf(Context, index))!= -1)
{
count++;
index += Context.length() -1;
System.out.println(index);
}
System.out.println(count);
A sample line is
[020t 12:23:43 FILE TAKEN
[020t 12:23:44 REGISTRATION END
[0r(1)2[000p[040qe1w3h162[020t*881*11/11/2010*12:24*
*CARD INSERTED*
[020t 12:24:06 CODE ENTERED
11\11\10 12:24 10390011
5061180101607659013 6598
INVALID TRANSACTION, PLEASE CONTACT
YOUR ADMINISTRATOR FOR ADVICE
I intend to pass the lines out to another method. Thanks
If you intend to pass the occurance, split the string based on new line. iterate the resultant string array and check if it starts with your needed string - if so you can add it some list and pass the list to your method
Related
So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.
In a larger project, I have created an ArrayList of Strings from a text file, where each line of the text file gets its own index in the ArrayList, so the lines are stored sequentially in the list.
I need the following method to return the next index in the ArrayList that contains an empty line. Since the lines are read in from a file, a line cannot be defined as null when it is read in... or at least I can't get it to work that way either.
Here is the code that I have so far:
public static int nextBlankIndex(int num){
//returns the index in the file input arraylist of the next blank line after line number "num"
//used to find spaces between questions
for(int i=0; i<in.size();i++)
{
String line = in.get(i);
if(line.equals(""));
return (num-1)+i;
}
return -1;
}
Any advice or edits greatly appreciated, as always. Thank you in advance.
It looks like you're adjusting the result by adding num-1 in the return statement. But you're not adding it in all the other places you use i, so the search always starts at the first line.
The easiest adjustment is to start the loop at i = num.
public static int nextBlankIndex(int num) {
for (int i = num; i < in.size(); i++) {
String line = in.get(i);
if (line.equals("")) {
return i;
}
}
return -1;
}
You also had a stray semi-colon after the if statement.
You want to start from num so start from it and just return the matching index
for(int i=num; i<in.size();i++)
{
String line = in.get(i);
if(line.equals(""))
return i;
}
I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );
In Java, I have a method that reads in a text file that has all the words in the dictionary, each on their own line.
It reads each line by using a for loop and adds each word to an ArrayList.
I want to get the length of the longest word (String) in the Array. In addition, I want to get the length of the longest word in the dictionary file. It would probably be easier to split this into several methods, but I don't know the syntax.
So far, the code is have is:
public class spellCheck {
static ArrayList <String> dictionary; //the dictonary file
/**
* load file
* #param fileName the file containing the dictionary
* #throws FileNotFoundException
*/
public static void loadDictionary(String fileName) throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));
while (in.hasNext())
{
for(int i = 0; i < fileName.length(); ++i)
{
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
Assuming that each word is on it's own line, you should be reading the file more like...
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
Remember, if you open a resource, you are responsible for closing. See The try-with-resources Statement for more details...
Calculating the metrics can be done after reading the file, but since your here, you could do something like...
int totalWordLength = 0;
String longest = "";
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
totalWordLength += dictionaryword.length();
dictionary.add(dictionaryword);
if (dictionaryword.length() > longest.length()) {
longest = dictionaryword;
}
}
int averageLength = Math.round(totalWordLength / (float)dictionary.size());
But you could just as easily loop through the dictionary and use the same idea
(nb- I've used local variables, so you will either want to make them class fields or return them wrapped in some kind of "metrics" class - your choice)
Set a two counters and a variable that holds the current longest word found before you start reading in with your while loop. To find the average have one counter be incremented by one each time the line is read and have the second counter add up the total number of characters in each word (obviously the total number of characters entered, divided by the total number of words read -- as denoted by the total number of lines -- is the average length of each word.
As for the longest word, set the longest word to be the empty string or some dummy value like a single character. Each time you read in a line compare the current word with the previously found longest word (using the .length() method on the String to find its length) and if its longer set a new longest word found
Also, if you have all this in a file, I'd use a buffered reader to read in your input data
May be this could help
String words = "Rookie never dissappoints, dont trust any Rookie";
// read your file to string if you get string while reading then you can use below code to do that.
String ss[] = words.split(" ");
List<String> list = Arrays.asList(ss);
Map<Integer,String> set = new Hashtable<Integer,String>();
int i =0;
for(String str : list)
{
set.put(str.length(), str);
System.out.println(list.get(i));
i++;
}
Set<Integer> keys = set.keySet();
System.out.println(keys);
System.out.println(set);
Object j[]= keys.toArray();
Arrays.sort(j);
Object max = j[j.length-1];
set.get(max);
System.out.println("Tha longest word is "+set.get(max));
System.out.println("Length is "+max);
I'm pretty new to programming and I'm getting a error which I'm sure is a easy fix for more experienced people.
Here is what I have:
import java.io.*;
import java.util.Scanner;
public class ReadNamesFile
{
public static void main(String[] args) throws IOException {
// make the names.csv comma-separated-values file available for reading
FileReader f = new FileReader("names.csv");
BufferedReader r = new BufferedReader(f);
//
String lastName="unknown", firstName="unknown", office="unknown";
// get first line
String line = r.readLine();
// process lines until end-of-file occurs
while ( line != null )
{
// get the last name on the line
//
// position of first comma
int positionOfComma = line.indexOf(",");
// extract the last name as a substring
lastName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the first name as a substring
firstName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the office number as a substring
office = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+2);
//
//
//
// display the information about each person
System.out.print("\nlast name = "+lastName);
System.out.print("\t first name = "+firstName);
System.out.print("\t office = "+office);
System.out.println();
//
// get the next line
line = r.readLine();
}
}
}
Basically, it finds the last name, first name and office number in a .csv file and prints them out.
When I compile I don't get any errors but when I run it I get:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)
Before trying to do the office number part, the first two (last and first name) printed out fine but the office number doesn't seem to work.
Any ideas?
Edit: Thanks for all the posts guys, I still can't really figure it out though. Can someone post something really dumbed down? I've been trying to fix this for an hour now and I can't get it.
Let's work by example, what issues you have with your code.
Eg: line: Overflow,stack
{ length: 14 }
Taking your program statements line by line -
int positionOfComma = line.indexOf(","); // returns 9
lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1
Now lastName has Overflow. positionOfComma has 9.
line = line.substring(positionOfComma+1);
Now line has stack.
firstName = line.substring(0,positionOfComma);
Asking substring from 0 to 9. But stack is only of length 5. This will cause String index out of range exeception. Hope you understood where you are doing wrong.
From JavaDoc:
(StringIndexOutOfBoundsException) - Thrown by String methods to
indicate that an index is either negative or greater than the size of
the string.
In your case, one of your calls to .substring is being given a value that is >= the length of the string. If line #34 is a comment, then it's the line above #34.
You need to:
a) Make sure you handle the case if you DON'T find a comma (i.e. if you cannot find and extract a lastName and/or firstName string)
b) Make sure the value of "positionOfComma + N" never exceeds the length of the string.
A couple of "if" blocks and/or "continue" statements will do the trick nicely ;-)
You correctly find positionOfComma, but then that logic applies to the original value of line. When you remove the last name and comma, positionOfComma is no longer correct as it applies to the old value of line.
int positionOfComma = line.indexOf(",");
this line of code might not find a comma and then positionOfComma will be -1. Next you substring something with (0,-1) - eeek no wonder it gives StringIndexOutOfBoundsException. Use something like:
int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
positionOfComma = line.indexOf(",");
}
You do have to do lots of checking of things sometimes especially when the data is whacked :(
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
PS I'm sure someone clever can make my coding look shabby but you get the point I hope :)