Im using the charAt function to find the first and second letters in a string that was read from a file but after getting the first character from the charAt(0) line, charAt(1), throws an exection that the string is too short when I know it is not. Here is the code.
while(inputFile.hasNext()){
//read file first line
String line = inputFile.nextLine();
//if the first 2 letters of the line the scanner is reading are the same
//as the search letters print the line and add one to the linesPrinted count
String lineOne = String.valueOf(line.charAt(0));
String lineTwo = String.valueOf(line.charAt(1));
String searchOne = String.valueOf(search.charAt(0));
String searchTwo = String.valueOf(search.charAt(1));
if (lineOne.compareToIgnoreCase(searchOne) == 0 && lineTwo.compareToIgnoreCase(searchTwo) == 0){
System.out.println(line);
linesPrinted++;
}
}
I've tried checking the make sure the string isn't being changed after the charAt(0) use by printing and I know it isn't and I've run the program with no probems after just removing the line so I am sure it is this that's causing the problem
The only functional change needed would to change hasNext to hasNextLine.
As one might encounter a line shorter than 2, say an empty line at the end of file, check the length.
while (inputFile.hasNextLine()) {
// read file next line
String line = inputFile.nextLine();
if (line.length() < 2) {
continue;
}
// if the first 2 letters of the line the scanner is reading are the same
// as the search letters print the line and add one to the linesPrinted count
String lineOne = line.substring(0, 1);
String lineTwo = lin.substring(1, 2);
String searchOne = search.substring(0, 1);
String searchTwo = search.substring(1, 2);
if (lineOne.equalsIgnoreCase(searchOne) && lineTwo.equalsIgnoreCase(searchTwo)) {
System.out.println(line);
linesPrinted++;
}
}
There is a problem with special chars and other languages, scripts. A Unicode code point (symbol, character) can be more than one java char.
while (inputFile.hasNextLine()) {
// read file next line
String line = inputFile.nextLine();
if (line.length() < 2) {
continue;
}
// if the first 2 letters of the line the scanner is reading are the same
// as the search letters print the line and add one to the linesPrinted count
int]} lineStart = line.codePoints().limit(2).toArray();
int]} searchStart = search.codePoints().limit(2).toArray();
String lineKey = new String(lineStart, 0, lineStart.length);
String searchKey = new String(searchStart, 0, searchStart.length);
if (lineKey.equalsIgnoreCase(searchKey)) {
System.out.println(line);
linesPrinted++;
}
}
Related
Could somebody explain what is wrong with this code. WHY is the if statement always false when it is matching the exact strings..I have tried it with == as well..Still, every time I am getting No Match Found !!.
String inData = "";
char inChar;
String property;
String a = "test";
void loop() {
Serial.println("String Comparison");
if(Serial.available() > 0){
while(Serial.available()>0) {
inChar = Serial.read();
inData.concat(inChar);
}
//Extracting Property
property = inData.substring(inData.lastIndexOf(":")+2); // Extracts the String "test"
Serial.println("Property:" +property);
if(property.equals(a)){ // It never matches though, it is TRUE all the time
Serial.println(" Matched !! ");
}
else
Serial.println(" Match Not Found !! ");
inData = "";
}
delay(5000);
}
Since I am able to see matches match and misses miss I think I need more information to replicate the error.
Since I don't see it happening I would guess it has to do with whatever the input is and how this line parses it.
property = inData.substring(inData.lastIndexOf(":")+2); // Extracts the String "test"
What is the current input that is failing?
Can you include your printed output with that input?
Add a line to print out property.length() to test for hidden whitespace characters
I am trying to read text from file, checking its content and then storing it in an array of string.
FileStream fs = new FileStream(pathToFiles, FileMode.Open);
StreamReader sr = new StreamReader(fs);
do{
line=sr.ReadLine();
if (line == "databases")
{
j = 0;
while ((ch = sr.Read()) != '}')
{
admin_databases[j] = sr.ReadLine();
j++;
}
}
else if (line == "table_name")
{
j = 0;
while ((ch = sr.Read()) != '}')
{
admin_table_name[j] = sr.ReadLine();
j++;
}
}
else
{
Response.Write(line+" ");
}
} while (line !=null);
The text is read by using ReadLine() method, but while checking its content
i.e
if(line=="databases")
it shows null string and hence unable to store it in an array.
what is the mistake that i am making here?
As an answer to last comments under main post :
According to what you say, we're back to whitespace theory !
A few tips :
Replace Response.Write(line+" "); by Response.Write("'" + line+"'"); just to see exact captured values.
Check your file content.
You could also replace your == operators by more specific comparisons : String.Compare with case insensitive param, or String.StartsWith() / Contains(), etc, rather than exact comparison.
You could also clean up your input string with "Trim()", etc.
Sorry, but we don't know what is in your file. Maybe problem is in any whitespaces.
In this line of code:
while ((ch = sr.Read()) != '}')
You missed one '='. It should look like that:
while ((ch == sr.Read()) != '}')
This is my first post so i apologize if it's not the best format. I'm student writing a code to import a document, read a line in the document and then reverse the letters in each word. The new word will be printed into a new file. For example "Jon 123" would be stored and written as "321 noJ". I have gotten the input to work but there is a problem with the writing of the line. The program is only writing the last word that is stored.
The abridged main method code is as follows:
//get first line of text
line = bw.readLine();
//while string is not null
while (line != null)
{
System.out.println ("Processing..."); //display message to show work being done
tokenLine = lineToken(line); //tokenize string
//to prevent exception from no token found
while (tokenLine.hasMoreTokens())
{
word = flipWord(tokenLine); //get next token and reverse letters
newLine = marginCheck(word); //store or write line depending on margin
flushClose(newLine); //write and flush buffer then close file
}
//move to next line in file
line = bw.readLine();
}
flushClose(newLine); //write and flush buffer then close file
//output completion message
System.out.println("The new file has been written.");
The relevant methods as follows:
public static StringTokenizer lineToken(String line)
{
//local constants
//local variables
StringTokenizer tokenLine; //store tokenized line
/******************* Start lineToken Method ***************/
tokenLine = new StringTokenizer(line); //tokenize the current line of text
return tokenLine;
}//end lineToken
public static String flipWord(StringTokenizer tokenLine)
{
//local constants
//local variables
String word; //store word for manipulation
String revWord = ""; //store characters as they are flipped
/******************************* Start flipWord Method******************/
//store the next token as a string
word = tokenLine.nextToken();
//for each character store that character to create a new word
for (int count = word.length(); count > 0; count--)
revWord = revWord + word.charAt(count - 1); //store the new word character by character
return revWord; //return the word reversed
}//end flipWord
public static String marginCheck(String revWord) throws Exception
{
//local constants
final int MARGIN = 60; //maximum characters per line
//local variables
String newLine = ""; //store the new line
FileWriter fw; //writes to output file
BufferedWriter bWriter; //instantiate buffered writer object
PrintWriter pw; //instantiate print writer object
String outFile = "RevWord.text"; //file to write to
/************* Start marginCheck Method ************/
//open the output file for writing
fw = new FileWriter(outFile);
bWriter = new BufferedWriter(fw);
pw = new PrintWriter(bWriter);
//if the buffered line concatenated with the word is less than the margins
if (newLine.length() + revWord.length() <= MARGIN)
newLine = newLine + revWord + " "; //the buffered line adds the word
else
//put an enline character at the end and write the line
newLine = newLine + "\n";
pw.println(newLine);
//use this word as the first word of the next line
newLine = revWord + " ";
return newLine; //return for use with flush
}//end marginCheck
public static void flushClose(String inLine) throws Exception
{
//local constants
//local variables
FileWriter fw; //writes to output file
BufferedWriter bWriter; //instantiate buffered writer object
String outFile = "RevWord.text"; //file to write to
/************ Start flushClose Method *********/
fw = new FileWriter(outFile);
bWriter = new BufferedWriter(fw); //initialize writer object
//write the last line to the output file then flush and close the buffer
bWriter.write (inLine);
bWriter.flush();
bWriter.close();
}//end flushClose
I am not sure, but my best guess is that every time you write to the file, you are overwriting the file, instead of appending to it.
Try FileWriter(outFile,true);
Answer from: http://www.mkyong.com/java/how-to-append-content-to-file-in-java/
my text file :
3.456 5.234 Saturday 4.15am
2.341 6.4556 Saturday 6.08am
At first line, I want to read 3.456 and 5.234 only.
At second line, I want to read 2.341 and 6.4556 only.
Same goes to following line if any.
Here's my code so far :
InputStream instream = openFileInput("myfilename.txt");
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line=null;
while (( line = buffreader.readLine()) != null) {
}
}
Thanks for showing some effort. Try this
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
double x = Double.parseDouble(parts[0]);
double y = Double.parseDouble(parts[1]);
}
I typed this from memory, so there might be syntax errors.
int linenumber = 1;
while((line = buffreader.readLine()) != null){
String [] parts = line.split(Pattern.quote(" "));
System.out.println("Line "+linenumber+"-> First Double: "+parts[0]+" Second Double:"
+parts[1]);
linenumber++;
}
The code of Bilbert is almost right. You should use a Pattern and call quote() for the split. This removes all whitespace from the array. Your problem would be, that you have a whitespace after every split in your array if you do it without pattern. Also i added a Linenumber to my output, so you can see which line contains what. It should work fine
I'm wondering how (and in which way it's best to do it) to split a string with a unknown number of spaces as separator in C++/CLI?
Edit: The problem is that the space number is unknown, so when I try to use the split method like this:
String^ line;
StreamReader^ SCR = gcnew StreamReader("input.txt");
while ((line = SCR->ReadLine()) != nullptr && line != nullptr)
{
if (line->IndexOf(' ') != -1)
for each (String^ SCS in line->Split(nullptr, 2))
{
//Load the lines...
}
}
And this is a example how Input.txt look:
ThisISSomeTxt<space><space><space><tab>PartNumberTwo<space>PartNumber3
When I then try to run the program the first line that is loaded is "ThisISSomeTxt" the second line that is loaded is "" (nothing), the third line that is loaded is also "" (nothing), the fourth line is also "" nothing, the fifth line that is loaded is " PartNumberTwo" and the sixth line is PartNumber3.
I only want ThisISSomeTxt and PartNumberTwo to be loaded :? How can I do this?
Why not just using System::String::Split(..)?
The following code example taken from http://msdn.microsoft.com/en-us/library/b873y76a(v=vs.80).aspx#Y0 , demonstrates how you can tokenize a string with the Split method.
using namespace System;
using namespace System::Collections;
int main()
{
String^ words = "this is a list of words, with: a bit of punctuation.";
array<Char>^chars = {' ',',','->',':'};
array<String^>^split = words->Split( chars );
IEnumerator^ myEnum = split->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ s = safe_cast<String^>(myEnum->Current);
if ( !s->Trim()->Equals( "" ) )
Console::WriteLine( s );
}
}
I think you can do what you need to do with the String.Split method.
First, I think you're expecting the 'count' parameter to work differently: You're passing in 2, and expecting the first and second results to be returned, and the third result to be thrown out. What it actually return is the first result, and the second & third results concatenated into one string. If all you want is ThisISSomeTxt and PartNumberTwo, you'll want to manually throw away results after the first 2.
As far as I can tell, you don't want any whitespace included in your return strings. If that's the case, I think this is what you want:
String^ line = "ThisISSomeTxt \tPartNumberTwo PartNumber3";
array<String^>^ split = line->Split((array<String^>^)nullptr, StringSplitOptions::RemoveEmptyEntries);
for(int i = 0; i < split->Length && i < 2; i++)
{
Debug::WriteLine("{0}: '{1}'", i, split[i]);
}
Results:
0: 'ThisISSomeTxt'
1: 'PartNumberTwo'