Eliminate the "\u3000" error in java - java

When I try to compile a java file, the compiler said "illegal character \u3000",
after searching, I find it is CJK Unified Ideographs
Chinese Korean and Japanese's SPACE. Instead of deleting the special SPACE manually, I decide to code a simple search-and-deleting java file to eliminate it.
However It doesnot point out the index error.
So how to write a code to eliminate this special SPACE
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class BufferReadAFile {
public static void main(String[] args) {
//BufferedReader br = null;
String sCurrentLine;
String message = "";
try {
/*br = new BufferedReader(new FileReader("/Users/apple/Test/Instance1.java"));
while ((sCurrentLine = br.readLine()) != null) {
message += sCurrentLine;
}
*/
String content = new Scanner(new File("/Users/apple/Coding/Instance1.java")).useDelimiter("\\Z").next();
//System.out.println(content);
searchSubString(content.toCharArray(),"\\u3000".toCharArray());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void searchSubString(char[] text, char[] ptrn) {
int i = 0, j = 0;
// pattern and text lengths
int ptrnLen = ptrn.length;
int txtLen = text.length;
// initialize new array and preprocess the pattern
int[] b = preProcessPattern(ptrn);
while (i < txtLen) {
while (j >= 0 && text[i] != ptrn[j]) {
j = b[j];
}
i++;
j++;
// a match is found
if (j == ptrnLen) {
System.out.println("found substring at index:" + (i - ptrnLen));
j = b[j];
}
}
}
public static int[] preProcessPattern(char[] ptrn) {
int i = 0, j = -1;
int ptrnLen = ptrn.length;
int[] b = new int[ptrnLen + 1];
b[i] = j;
while (i < ptrnLen) {
while (j >= 0 && ptrn[i] != ptrn[j]) {
// if there is mismatch consider the next widest border
// The borders to be examined are obtained in decreasing order from
// the values b[i], b[b[i]] etc.
j = b[j];
}
i++;
j++;
b[i] = j;
}
return b;
}
}

I don't think "\\u3000" is what you want. You can print out the string and see the content yourself. You should use "\u3000" instead. Note the single back slash.
System.out.println("\\u3000"); // This prints out \u3000
System.out.println("\u3000"); // This prints out the CJK space
Alternatively, you could just use the actual CJK space character directly as in one of the if checks in your CheckEmpty class.

In my Question, I am trying to use KMP alogrithm to search the index of a pattern in my java file
if we use "\\u3000".toCharArray() the compiler will look through each character. Which is not what we want. \\u3000 is an special white space. It is FULL-WIDTH space that only existed in Chinese Korean and Japanese languages.
If we trying to write sentence by using the FULL-WIDTH Space. It will look like:
Here is Full-width demonstration.
Very distinctive space. but is not so visible in java file. It inspire me to write the code below
import java.util.*;
import java.io.*;
public class CheckEmpty{
public static void main(String []args){
try{
String content = new Scanner(new File("/Users/apple/Coding/Instance1.java")).useDelimiter("\\Z").next();
if(content.contains(" ")){
System.out.println("English Space");
}
if(content.contains("\\u3000")){
System.out.println("Backslash 3000");
}
if(content.contains(" ")){// notice the space is a SPECIAL SPACE
System.out.println("C J K fullwidth");
//Chinese Japanese Korean white space
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
As expected, the result shows:
which means the java file contains both the normal and full-width Space.
After that I am thinking to write another java file to delete all the special space:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.*;
public class DeleteTheSpecialSpace {
public static void main(String[] args) {
//BufferedReader br = null;
String sCurrentLine;
String message = "";
try {
String content = new Scanner(new File("/Users/apple/Coding/Instance1.java")).useDelimiter("\\Z").next();
content.replaceAll(" ",""); // notice the left parameter is a SPECIAL SPACE
//System.out.println(content);
PrintWriter out = new PrintWriter( "/Users/apple/Coding/Instance1.java" );
out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Finally: amazing things happen, There is no error in "Instance1.java", since all full-width space have been eliminated
Compile SUCCESS :)

Related

Why is my FileReader/BufferReader returning both the sentence and null?

The main thing I am trying to do is input a .txt file into a 2d char array. The problem is that no data is being saved into the array, so I'm thinking my problem lies with the fact that there is no in-between string from the .txt file to the array. I tried using file and buffered readers so I would have a string, and it works, but it adds null many many times. Can someone point out what I am doing wrong here? (I am very new to java, sorry for any errors in question format and such)
See code below, where I'm encountering the problem.
Scanner scanner = new Scanner(new File("Code.txt"));
try {
//had a problem trying to just get the chars out from a file just as a string
// so to a filereader we go!
FileReader Enigma = new FileReader("Code.txt");
// when looking at filereaders, i found bufferedreaders
// they seem to help with reading chars better than the filereader alone
BufferedReader CryptoMachine = new BufferedReader(Enigma);
for (i = 0; i <= rows-1; i++)
{
for (j = 0; j <= columns-1; j++)
{
sentence = CryptoMachine.readLine();
System.out.print(sentence);
}
}
CryptoMachine.close();
}
catch (FileNotFoundException e) {
System.out.println("No file found");
}
Return I get:
This is ridiculously hardnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnull
Whole code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
// TODO block code
public class Enigma {
// TODO block code
public static void main(String[] args) throws IOException {
// double array set up here
String sentence = "";
int rows = 6;
int columns = 7;
char[][] RotaryMachine = new char[rows][columns];
boolean flag = false;
// told this lets me declare variables on the same line
int i = 0,j = 0;
// scanner to scan a file here
Scanner scanner = new Scanner(new File("Code.txt"));
try {
//had a problem trying to just get the chars out from a file just as a string
// so to a filereader we go!
FileReader Enigma = new FileReader("Code.txt");
// when looking at filereaders, i found bufferedreaders
// they seem to help with reading chars better than the filereader alone
BufferedReader CryptoMachine = new BufferedReader(Enigma);
for (i = 0; i <= rows-1; i++)
{
for (j = 0; j <= columns-1; j++)
{
sentence = CryptoMachine.readLine();
System.out.print(sentence);
}
}
CryptoMachine.close();
}
catch (FileNotFoundException e) {
System.out.println("No file found");
}
for(i = 0; j > columns && !flag;++i)
{
if(i < rows && !scanner.hasNext())
{
System.out.println("The English have our codes");
flag = true;
}
RotaryMachine[i][j] = scanner.next().charAt(0);
if(i > 6)
{
j++;
}
RotaryMachine[i][j] = '*';
}
// RotaryMachine[0][0] = 'a';
//now, to hopefully code the scrambler section properly, for Enigma to work!
// V2 seems to keep letters really close together
for(i=0;i < columns;++i)
{
for(j = 0;j < rows;++j)
{
System.out.printf("%c", RotaryMachine[j][i]);
}
}
// V1 of the code seems to space out the letters
// for(j=0;j < rows;++j)
// {
// for(i = 0;i < columns;++i)
// {
// System.out.printf("%c", RotaryMachine[j][i]);
// }
// }
}
}
Since the file being read only has one line, readLine will return null for every call past the first since there are no more lines to read.
You can String.split the initial string after reading it if you so desire.

Read a csv that has double quotes with comma inside

UPDATE: WORKING SOLUTION POSTED BELOW
I'm trying to process a csv file and I'm splitting it by comma. However, there are couple places with quotes that has comma embedded.
Example: "# 29. Toxic substances properly identified, stored, used"
Every quote that has a comma in there is wrapped around with " ", is there a way to detect this double quotes and work around the commas?
Thanks!
Original code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
import java.io.PrintWriter;
public class csvFileReader {
public static void main(String[] args) {
String csvFile = "/Users/zzmle/Desktop/data.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
int count=0;
try {
br = new BufferedReader(new FileReader(csvFile));
String firstline = br.readLine();
String[] header = firstline.split(",");
while ((line = br.readLine()) != null && count<10) {
//comma is the separator
String[] Restaurant = line.split(cvsSplitBy);
for (int i=0; i<header.length; i++) {
System.out.println(header[i]+": "+Restaurant[i]+" ");
}
System.out.println("-------------------");
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Working Solution:
// #author Zhiming Zhao
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
import java.io.PrintWriter;
public class csvFileReader {
public static void main(String[] args) {
String csvFile = "data.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
int count=0;
try {
br = new BufferedReader(new FileReader(csvFile));
String firstline = br.readLine();
String[] header = firstline.split(cvsSplitBy);
while ((line = br.readLine()) != null && count<10) { //count<10 is for testing purposes
String[] Restaurant = line.split(cvsSplitBy); //comma is the separator
process(Restaurant); //this is to deal with the commas within quotation marks (which split the elements and shifts them into the wrong places)
//this part prints the header + restaurant for the first ten lines
for (int i=0; i<header.length; i++) {
System.out.println(header[i]+": "+Restaurant[i]+" ");
}
System.out.println("-------------------");
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("The file cannot be found, check if the file is under root directory");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Input & Output operations error");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// #brief This function specifically deal with the issue of commas within the quotation marks
// #detail it gets the index number of the 2 elements containing the quotation marks, then concats them all. It works with multiple quotation marks on the same line
public static void process(String[] data) {
int index1 = -1; //initialize the index of the first ", -1 for empty
int index2 = 0; //initialize the index of the second ", 0 for empty
for (int i=0; i<data.length; i++) {
if (String.valueOf(data[i].charAt(0)).equals("\"") && index1 == -1) { //if index1 is not empty and the first char of current element is "
index1 = i; //set index1 to current index number
}
if (String.valueOf(data[i].charAt(data[i].length()-1)).equals("\"") && index1 != -1) { //if index1 is not empty and the last char of current element is "
index2 = i; //set index2 to current index number
multiconcat(index1, index2, data); //concat the elements between index1 and index2
data = multidelet(index1+1, index2, data); //delete the elements that were copied (index1+1:index2)
i -= (index2-index1); //this is to reset the cursor back to index1 (could be replaced with i = index1)
index1 = -1; //set index1 to empty
}
}
}
// #brief Copy all elements between index1 and index2 to index1, doesn't return anything
public static void multiconcat(int index1, int index2, String[] data) {
for (int i=index1+1; i<=index2; i++) {
data[index1] += data[i];
}
}
// #brief Deletes the elements between index1+1 and index2
public static String[] multidelet(int index1, int index2, String[] data) {
String[] newarr = new String[data.length-(index2-index1+1)];
int n = 0;
for (int i=0; i<data.length; i++) {
if (index1 <= i && i <= index2) continue;
newarr[n] = data[i];
n++;
}
return newarr;
}
}
The csv file
Output (one of the lines with quotation mark and comma embedded), although it's not perfect (the comma within quotation mark got eaten), it's a minor issue and I'm too lazy to fix it lol :
serial_number: DA08R0TCU
activity_date: 03/30/2018 12:00:00 AM
facility_name: KRUANG TEDD
violation_code: F035
violation_description: "# 35. Equipment/Utensils - approved; installed; clean; good repair capacity"
violation_status: capacity"
points: OUT OF COMPLIANCE
grade: 1
facility_address: A
facility_city: 5151 HOLLYWOOD BLVD
facility_id: LOS ANGELES
facility_state: FA0064949
facility_zip: CA
employee_id: 90027
owner_id: EE0000857
owner_name: OW0001034
pe_description: 5151 HOLLYWOOD LLC
program_element_pe: RESTAURANT (31-60) SEATS HIGH RISK
program_name: 1635
program_status: KRUANG TEDD
record_id: ACTIVE
score: PR0031205
service_code: 92
service_description: 1
row_id: ROUTINE INSPECTION ```
My own solution:
Read the first character of each element, if the first character is a double quote, concat this and the next ones (will need to use recursion for this) until there's an element with a double quote as the last character.
This will run considerably faster than reading char by char, as suggested by JGFMK.
And I am not allowed to use external libraries for this project.
STILL IMPLEMENTING THIS, I will update if it works
EDIT: Working solution posted in original post
don't reinvent the wheel: there are libs to read csv around e.g. http://commons.apache.org/proper/commons-csv/
http://opencsv.sourceforge.net/
https://code.google.com/archive/p/jcsv/

Java FileInputStream Issues(Extra Whitespace)

When I use FileInputStream to input text from my spawn.txt file for a tile-based map, it adds extra whitespace in-between each line.
package mapInit;
import java.io.FileInputStream;
public class SpawnMap {
static char[][] spawnWorld = new char[30][30];
public static void main(String[] args) {
try {
FileInputStream spawn = new FileInputStream("Resources/Map/spawn.txt");
int i = 0;
int h = 0;
int k = 0;
while((i=spawn.read())!=-1){
if(h == 30) {
h = 0;
k++;
}
spawnWorld[k][h] = (char)i;
h++;
}
spawn.close();
} catch (Exception e) {
}
for (int i=0; i<30; i++) {
for (int j=0;j<30;j++) {
System.out.println(spawnWorld[i][j]);
}
}
}
}
This is the result of the output loop:
This is a picture of the text file:
GitHub Link: https://github.com/WeaponGod243/Machlandia
I think Scanner class it's more suitable for your task
Scanner class in Java is found in the java.util package. Java provides
various ways to read input from the keyboard, the java.util.Scanner
class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter
which is whitespace by default. It provides many methods to read and
parse various primitive values.
The Java Scanner class is widely used to parse text for strings and
primitive types using a regular expression. It is the simplest way to
get input in Java. By the help of Scanner in Java, we can get input
from the user in primitive types such as int, long, double, byte,
float, short, etc.
The Java Scanner class extends Object class and implements Iterator
and Closeable interfaces.
The Java Scanner class provides nextXXX() methods to return the type
of value such as nextInt(), nextByte(), nextShort(), next(),
nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a
single character from the scanner, you can call next().charAt(0)
method which returns a single character.
Source
Scanner Java Doc
public static void main(String arg[]) {
try (Scanner sc = new Scanner(new File("Resources/Map/spawn.txt"))) {
// Checking if sc has another token in the file
while(sc.hasNext()) {
// Print line
System.out.println(sc.next());
}
} catch (Exception ex) {
// Use a Logger to log exceptions in real projects
ex.printStackTrace();
}
}
You could use Apache Commons IO library too
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
try {
File f = new File("Resources/Map/spawn.txt");
List<String> lines = FileUtils.readLines(f, "UTF-8");
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
// Use a Logger to log exceptions in real projects
e.printStackTrace();
}
}
}
Change the System.out.println inside your loop to just System.out.print.
System.out.println will automatically add a newline character every time, even if you're only printing a single character. System.out.print will take the String you pass in, and print it as is.
Here's a link to the official Javadoc:
https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#print-java.lang.String-
Also, unless it's on purpose, verify you're not printing the \n (newline character) at the end of each line. If you actually want to start a new line at the end of each line, simply put a System.out.println(); line after the end of the innermost loop.
I have looked at your codes. It seems by using this I have detected that by using FileInputStream it will produce an empty space in between the values.
static char[][] spawnWorld = new char[30][30];
public static void main(String[] args) {
try {
FileInputStream spawn = new FileInputStream("C:/Daniel/spawn.txt");
int i = 0;
int h = 0;
int k = 0;
while ((i = spawn.read()) != -1) {
if (h == 30) {
h = 0;
k++;
}
spawnWorld[k][h] = (char) i;
if (h == 19) System.out.println((char) i);
System.out.println("[" + k + "][" + h + "] : " + i);
h++;
}
spawn.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Start Printing");
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
System.out.println("[" + i + "][" + j + "] : " + spawnWorld[i][j]);
}
}
System.exit(0);
}
From then on you may debug it accordingly.
At line 19, your 'i' returns a blank space or char value i.
I would suggest to use the Scanner as your way to read the file instead.
A text file is made up of characters on a line followed by end-of-line sequences, typically newlines or carriage returns followed by newlines. (These can also be thought of as line separators rather than line endings, and the last line might not be followed by one, depending on how the file was created.) You are reading the file character by character but you make no allowance for these end of line characters.
It doesn't make any difference whether you use FileInputStream or Scanner; the problem is, you read the file one character at a time but don't account for carriage return and newline.
For example:
while ((i=spawn.read()) != -1) {
if (Character.isWhitespace((char)i)) {
continue;
}
if (h == 30) {
h = 0;
k++;
}
spawnWorld[k][h] = (char)i;
h++;
}

Comprehending these JUnit tests results

I am doing some exercises for my CS course and they are giving us Junit tests however they only tell us if we fail or pass. The output/expected output is jibberish to me.
I am given expected output/output in this fashion:
java.lang.AssertionError: expected <3143794514> but was <459133821>
I notice that the value <459133821L> is also found in the code of the test. However, I'm still a beginner. Apparently adler32 is meant to check for errors through checksums, but I don't know how to utilize this. Is there some way to have this show more meaningful messages so I know what is going wrong with my code?
E.g: I am expected to count all the words in a string. Can these tests show me what input/output is returning the incorrect answer?
Here is a sample of the JUnit class:
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.io.*;
import java.util.zip.Adler32;
public class TestStringProblems {
private static final int RUNS = 100000;
private static final int SEED = 12345;
private StringProblems sp = new StringProblems();
#Test
public void testCountWords() {
BufferedReader br = null;
Adler32 check = new Adler32();
int count = 0;
try {
br = new BufferedReader(new FileReader("warandpeace.txt"));
String line = br.readLine();
while(line != null) {
int words = sp.countWords(line.trim());
count += words;
check.update(words);
line = br.readLine();
}
} catch(IOException e) { System.out.println("Error: " + e); assertTrue(false); }
finally { try { br.close(); } catch(Exception e) { } }
assertEquals(count, 562491); // number of words in War and Peace
assertEquals(check.getValue(), 2309395892L); // checksum of word counts
}
#Test
public void testRemoveDuplicates() {
Adler32 check = new Adler32();
java.util.Random rng = new java.util.Random(SEED);
for(int i = 0; i < RUNS; i++) {
StringBuilder sb = new StringBuilder();
int len = rng.nextInt(500);
for(int j = 0; j < len; j++) {
char c = (char)(1 + rng.nextInt(50000));
int rep = rng.nextInt(10) + 1;
for(int k = 0; k < rep; k++) {
sb.append(c);
}
}
check.update(sp.removeDuplicates(sb.toString()).getBytes());
}
assertEquals(check.getValue(), 459133821L);
}
}
Thanks.
public class StringProblems {
public String removeDuplicates(String s) {
String newStr = "";
if (s.length() == 0) {
return s;
}
int length = s.length() - 1;
for(int i = 0;i<length+1;i++) {
if(i!=0 && s.charAt(i)!=s.charAt(i-1)) {
newStr += s.charAt(i);
}
}
return s.charAt(0) + newStr;
}
public int countWords(String s) {
String newStr = s.trim(); // removes unnecessary whitespace
if (newStr.isEmpty()) {
return 0;
}
return newStr.split("\\W+").length; // should work since it creates an array of substrings,
// length should indicate how many substrings are in the new string
}
}
You're "expected" and "actuals" are backward.
http://junit.sourceforge.net/javadoc/org/junit/Assert.html
The first parameter to assertEquals is EXPECTED, the second is ACTUAL.
The error you are seeing is obviously firing on this line: assertEquals(check.getValue(), 459133821L);
You need to swap your expected and actuals and THEN ALSO fix your calculations. You're still getting the wrong answer if you are trying to get 459133821L. I haven't looked over all of your code, but these tests are showing you the input output and what is giving you the correct answer. Figure out why you are trying to hit 459133821L in testRemoveDuplicates (which at a glance seems to be using a random so I'm not sure how you know what to expect), and you'll solve it.

How to read certain chunks of a text file. Java

So I have a text file (file.txt) that has a long number in it. Basically, the number is like that of PI. I need to read that number 10 digits at a time from the file. For example:
Number in the file:
3.14159265358979323846264338327950288419716939937510582097494459230781640628
I need to take the first ten digits of it: 3.141592653 and pass it into a function that
returns true or false. If I receive a true, then the function stops and returns those 10
digits. If the number is false, then I take the next 10 digits, 1415926535, and pass it
into the function.
How would I go about reading the file the 10 digits at a time.
you can get this line to String variable and substring it using '.'
Then get only the decimal part and chunk them in the size of 10 and store it into an array.
If you post your code we can help more than this.
To chunk you can use substring
Did Something like this , hope its useful, I hardcoded the value assuming you get the value from text file
package javaapplication14;
public class JavaApplication14 {
static int strt = 0;
static int end = 10;
public static void main(String[] args) {
String num = "3.14159265358979323846264338327950288419716939937510582097494459230781640628";
boolean val = false;
while (val == false) {
val = check(num.substring(strt, end));
strt = end;
end = end + 10;
}
}
private static boolean check(String substring) {
String num = substring;
//just for checking (the first ten digits of the string)
String chk = "3.14159265";
System.out.println("substr " + substring);
if (chk.equals(num)) {
System.out.println("equal");
return true;
} else {
return false;
}
}
}
Here's some generic code which should get you started:
String text;
int index = 0;
String subText = text.substring(index, index+10);
while (method(subText) && ((index + 10) < text.length())) {
subText = text.substring(index, index + 10);
index += 10;
}
Using Apache Commons IO:
import java.io.File;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;
...
String fileContent = FileUtils.readFileToString(new File("pi.txt"));
String tenCharacters = Arrays.toString(fileContent.split("(?<=\\G..........)"));
doStuff(tenCharacters);
...
Alright, here is a draft, build this logic into your existing code, edit your question and we can help you to finalize it.
Key Methods to use are FileReaders read() Method to get a single char (or -1 if there are no more) and skip() to ignore a certain amount of chars (already processed)
(Sorry the bad formating im a bit in a hurry)
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class SimpleReader {
File theSourceFile = new File("D:\\<yourPath>\\input.txt");
int nrOfCharsToRead = 10;
int nrOfCharsProcessed = 0;
public static void main(String[] args) {
new SimpleReader().process();
}
public void process(){
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
System.out.println(getNext(nrOfCharsToRead));
}
private String getNext(int nrOfCharsToRead){
try {
FileReader reader = new FileReader(theSourceFile);
StringBuffer b = new StringBuffer();
reader.skip(nrOfCharsProcessed);
char c;
int counter = 0;
StringBuffer sb = new StringBuffer();
while((c = (char) reader.read()) != -1 && counter < nrOfCharsToRead){
sb.append(c);
nrOfCharsProcessed++;
counter++;
}
reader.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
String text;
text = "3.14159265358979323846264338327950288419716939937510582097494459230781640628";
int index = 0;
while (index<text.length()) {
String string = text.substring(index, Math.min(index+10,text.length()));
//function to process 10 digits. if true break
if(processDigits(string))
break;
index+=10;
}

Categories