Attempting to utilize text captured from a PDF - java

I have an array called myArray that contains words separated by a space and trimmed from a PDF from the first page to the last page. I wrote a simple print array method that iterates through and prints each element one by one and it looks great!
Immediately after I have it go through another for loop for the length of the array and checks if (myArray[i].equals("(19)")) {//print something} When printing the array to the console it is clear that the value (19) exists in the array.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray;
static String[] events = {"400", "800", "1500",
"3000", "5000", "10000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
printArray(myArray);
//System.out.println();
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
if (!currentEvent.equals("")) {
if (myArray[i].charAt(0) == '(' && (myArray[i].charAt(myArray[i].length() - 1) == ')')) {
String formatedRunners = "";
//It is possible to see some numbers such as (19)) or (19)
if (containsCharacter(myArray[i], ')') == 2) {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 2);
} else {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 1);
}
int numberOfRunners = Integer.parseInt(formatedRunners);
int distance = Integer.parseInt(currentEvent);
sum += numberOfRunners * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static void readFile() {
Scanner c = new Scanner(System.in);
System.out.println("Enter a file path: ");
String filePath = c.nextLine();
file = new File(filePath);
}
public static void parsePDF(File file) throws IOException {
textStripper = new PDFTextStripper();
pdDoc = PDDocument.load(file);
//Parse PDF
textStripper.setStartPage(1);
//textStripper.setEndPage();
//Parsed String
parsedText = textStripper.getText(pdDoc);
}
public static boolean contains(String s) {
for (int i = 0; i < events.length; i++) {
if (s.equals(events[i])) {
return true;
}
}
return false;
}
public static void printArray(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].equals("")) {
//Use some filler to avoid crashes when checking characters
myArray[i] = "NULL";
}
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
public static int containsCharacter(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
}
Here is what I want:
Parsing and trimming etc. (OK)
Iterating over myArray (in the main method) and detecting events (OK)
If an event occurred then the next value must be (Any number) like (19)
(NOK)
The number from step 3. will be used to compute another number
Reset the current event to repeat the process over and
over again.
It seems like that it is reading each event correctly but only picks up (19)) instead of (19).

There are several problems in you code (No Exceptionhandling, everything static, small bugs etc.) but I will focus on the major issue. (I removed the code which I did not change)
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray = {"Seeded", "3000", "random", 25, "(44)", "1500", "random", "(13)"};
static String[] events = {"400", "800", "1500", "3000", "5000", "10000", "200.000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
else if (!currentEvent.isEmpty()) {
Integer value = extractNumber(myArray[i]);
if (!myArray[i].isEmpty() && value!=null) {
int distance = Integer.parseInt(currentEvent);
sum += value.intValue() * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static Integer extractNumber(String toCheck) {
Pattern r = Pattern.compile("^.*?\\([^\\d]*(\\d+)[^\\d]*\\).*$");
Matcher m = r.matcher(toCheck);
if(m.find()) {
return Integer.valueOf(m.group(1));
}
return null;
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
The result is
151500 meters
94 miles

Related

Difficulty reading .txt data when running Stable Marriage algorithm in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am new to Java and I am trying to execute the code below regarding Stable Marrage algorithm, but when executing the code below you get the following error:
Error: For input string: "3 " Exception in thread "main"
java.lang.NullPointerException at
br.com.entrada.GaleShapley.(GaleShapley.java:21) at
br.com.entrada.GaleShapley.main(GaleShapley.java:166)
Gale Shapley Marriage Algorithm
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args)
{
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = {"1", "2", "3"};
/** list of women **/
String[] w = {"1", "2", "3"};
/** men preference **/
String[][] mp = null ;
/** women preference **/
String[][] wp= null ;
// Input.txt is like
// 3 <--defines the size of array
// male preference array
// 1 3 2
// 1 2 3
// 2 3 1
//female preference array
//1 3 2
//2 1 3
//2 1 3
try{
FileInputStream fstream = new FileInputStream("input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line=0;
int k=0;
int n=0;
int i=0;
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
GaleShapley gs = new GaleShapley(m, w, mp, wp);
}
}
The program is not reading the input.txt input file completely. It is reading only the first line of this file. And I can't solve this. I think the problem should be in the code part below.
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
Below is the input file: input.txt
3
male preference array
1 3 2
1 2 3
2 3 1
female preference array
1 3 2
2 1 3
2 1 3
The error is thrown due this : 3 => it contains a whitespace
And when you call the Integer.parse(N), N cannot be parsed to Integer while there's this whitespaces,
To resolve this, i used strLine.trim();
women[i].equals(str) : you are comparing here a string to an Integer is always false and the result of your function womenIndexOf is -1, and this is going to throw an exception of IndexOutOfBounds Exception when using the -1 as index
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley {
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley() {
}
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp) {
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches() {
while (engagedCount < N) {
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++) {
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null) {
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
} else {
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index)) {
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
engagedCount++;
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index) {
for (int i = 0; i < N; i++) {
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str) {
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str) {
for (int i = 0; i < N; i++) {
if (women[i].equals(str))
return i;
}
return -1;
}
/** print couples **/
public void printCouples() {
System.out.println("Couples are : ");
for (int i = 0; i < N; i++) {
System.out.println(womenPartner[i] + " " + women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("C:\\Users\\Youssef\\Projects\\STS\\TEST\\src\\input");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
Follows the code running below:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
public GaleShapley() {}
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("src\\input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
The result is:
Gale Shapley Marriage Algorithm
Couples are :
1 1
2 2
3 3

My Program stops printing to console, but continues to run in background. No Exception is thrown

My program Runs and prints the first few system.out statements, then stops printing them. There is no exception thrown, and the program continues to run until manually terminated.
I've tried System.out.flush(); but am not even sure where to put that
import java.io.*;
import java.util.ArrayList;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws
FileNotFoundException {
String inputFileStr = args[0];//"input.txt";
String outputFileStr = args[1];//"output.txt";
String deleteFileStr = args[2];//"CS401Project5Delete_Varner_Sav58.txt";//
String replaceFileStr = args[3]; //"CS401Project5Replace_VARNER_SAV58.txt";
// create files w/ corresponding file names
try{
File inputFile = new File(inputFileStr);
File outputFile = new File(outputFileStr);
File deleteFile = new File(deleteFileStr);
File replaceFile = new File(replaceFileStr);
// create arrayLists
ArrayList<StringBuilder> deleteArray;
ArrayList<StringBuilder> replaceArray;
ArrayList<StringBuilder> inputArray;
ArrayList<String> inputStringArray = new ArrayList<>();
ArrayList<String> tokensArray = new ArrayList<>();
ArrayList<Integer> frequenciesArray = new ArrayList<>();
// turn Files into arrayLists of StringBuilders
deleteArray = fileToArray(deleteFile);
replaceArray = fileToArray(replaceFile);
inputArray = fileToArray(inputFile);
System.out.println("# words in original file: " + wordCount(inputArray));
// create a deleteList object
DeleteList delete = new DeleteList();
delete.compareArray(inputArray, deleteArray);
System.out.println("Word Count After Deleteing noise: " + delete.wordCount(inputArray));
System.out.flush();
// create a replacelist object
ReplaceList replace = new ReplaceList();
replace.compareArray(inputArray, replaceArray);
System.out.println("Word count after replacing words: " + replace.wordCount(inputArray));
System.out.println("New input printed to 'output.txt'");
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
// turns a file into an arraylist of string builders
public static ArrayList<StringBuilder> fileToArray(File fileName) throws FileNotFoundException {
ArrayList<String> array = new ArrayList<>();
ArrayList<StringBuilder> sbArray = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null)
{
if (!line.isEmpty()) {
Stream.of(line.split("\\s+")).forEachOrdered(word -> array.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
for(int i = 0; i < array.size(); i++) {
StringBuilder sb = new StringBuilder();
sb.append(array.get(i));
sbArray.add(sb);
}
for(int i = 0; i < sbArray.size(); i ++) {
if
(sbArray.get(i).toString().endsWith(",") ||
sbArray.get(i).toString().endsWith(".") ||
sbArray.get(i).toString().endsWith(" ")
||sbArray.get(i).toString().endsWith(":")) {
sbArray.get(i).deleteCharAt(array.get(i).length() - 1);
}
}
return sbArray;
}
public static int wordCount(ArrayList<StringBuilder> array) {
int count = 0;
for (int i = 0; i < array.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class DeleteList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
//constructor
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> deleteArray) {
for (int i = 0; i < deleteArray.size(); i++) {
for (int j = 0; j < inputArray.size(); j++) {
if (deleteArray.get(i).toString().equals(inputArray.get(j).toString())){
inputArray.remove(j);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class ReplaceList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> replaceArray) {
String wordToReplace, wordReplacingWith = null;
for (int i = 0; i < replaceArray.size(); i++) {
wordToReplace = replaceArray.get(i).toString();
wordReplacingWith = replaceArray.get(i +1).toString();
for (int j = 0; j < inputArray.size(); j++) {
if (inputArray.get(j).toString().equalsIgnoreCase((wordToReplace))) {
StringBuilder strB = new StringBuilder();
strB.append(wordReplacingWith);
inputArray.set(j, strB);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
It should be printing to the console:
words in the original file :
words after deleting noise:
words after replacing words:
New Input printed to "output.txt" <--- (i haven't coded this part yet)
Note:
I have to use string builders, implement an interface, and have the
delteList and replaceList extend ArrayList & handle all exceptions in
main
You're problem is this:
ReplaceList#compareArray
while (i < replaceArray.size()) {
wordReplacingWith = replaceArray.get(i + 1).toString();
}
You probably want to increment i at some point or more likely you need a different counter here.
And those System.exit() commands that prevent compilation ;)
The only thing I am seeing in the updated version is a potential ArrayIndexOutOfBoundsException for
for (int i = 0; i < replaceArray.size(); i++) {
...
wordReplacingWith = replaceArray.get(i +1).toString();
...
}
Unrelated to any endless loop problem you might still have:
DeleteList#compareArray is likely to skip elements after a remove operation,
as the new element on position j (the former j+1) element is not covered by your loop.

Not printing same output

Simply not printing the same output as the line above and I can't figure out why this is happening, I've noticed that it's printing the last N numbers from the end backwards, whatever i input into the parameter it prints that amount a second time.
Here's the main
public class main {
public static void main(String args[]) {
ScalesSolution s1 = new ScalesSolution(11);
s1.println();
ScalesSolution s2 = new ScalesSolution(s1.GetSol());
s2.println();
}
}
Heres the ScalesSolution Class
import java.util.ArrayList;
import java.util.Random;
public class ScalesSolution {
private String scasol;
public void print() {
System.out.print(scasol);
}
// Display the string with a new line
public void println() {
print();
System.out.println();
}
public String GetSol()
{
return scasol;
}
}
Heres the randomOther Class
import java.util.*;
import java.io.*;
public class randomOther {
// Shared random object
static private Random rand;
// Create a uniformly distributed random integer between aa and bb inclusive
static public int UI(int aa, int bb) {
int a = Math.min(aa, bb);
int b = Math.max(aa, bb);
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
int d = b - a + 1;
int x = rand.nextInt(d) + a;
return (x);
}
// Create a uniformly distributed random double between a and b inclusive
static public double UR(double a, double b) {
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
return ((b - a) * rand.nextDouble() + a);
}
static public ArrayList<Double> ReadNumberFile(String filename) {
ArrayList<Double> res = new ArrayList<Double>();
Reader r;
try {
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER) {
res.add(stok.nval);
}
stok.nextToken();
}
} catch (Exception E) {
System.out.println("+++ReadFile: " + E.getMessage());
}
return (res);
}
}
Here is the issue the Output:
00101001010101101011001011010101101001011010001011010010101101001001011010010
01011010010
I believe that both outputs should be the same and I see that there is a problem here, not sure why they aren't
I see that the way your are using System.out.print inside your RandomBinaryString(int n) is causing confusion. It is printing and appending to the String s. Try to avoid that. Replacing the System.out.print(s += '0'); and System.out.print(s += '1'); with s += '0'; and s += '1';in the RandomBinaryString will fix your output.
Use the snippet below in your code:
private static String RandomBinaryString(int n) {
String s = new String();
// Code goes here
// Create a random binary string of just ones and zeros of length n
for (int i = 0; i < n; i++) {
int y = randomOther.UI(0, 1);
if (y == 0) {
s += '0';// this line here was changed
} else {
s += '1';// and this line here was changed too
}
}
return (s);
}
Hope this helps!

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

Request File Name as Input --Java

My code at the moment:
import java.util.*;
import java.io.*;
public class Percolation {
// given an N-by-N matrix of open sites, return an N-by-N matrix
// of sites reachable from the top via a vertical path of open sites
private static Scanner scan = null;
public static boolean[][] readOpenFromFile() {
final File f = new File("file.txt");
try {
scan = new Scanner(f);
}
catch(FileNotFoundException ex) {
System.exit(0);
}
final int m = scan.nextInt();
final int n = scan.nextInt();
final boolean[][] grid = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
grid[i][j] = readBoolean();
}
}
return grid;
}
public static boolean readBoolean() {
final String s = scan.next();
if(s.equalsIgnoreCase("true")) {
return true;
}
if(s.equalsIgnoreCase("false")) {
return false;
}
if(s.equals("1")) {
return true;
}
if(s.equals("0")) {
return false;
}
throw new java.util.InputMismatchException();
}
public static boolean[][] flow(final boolean[][] open) {
final int n = open.length;
final boolean[][] full = new boolean[n][n];
for(int j = 0; j < n; j++) {
flow(open, full, 0, j);
}
return full;
}
public static void flow(final boolean[][] open, final boolean[][] full, final int i, final int j) {
final int n = open.length;
// base cases
if(( i < 0) ||( i >= n)) {
return; // invalid row
}
if(( j < 0) ||( j >= n)) {
return; // invalid column
}
if(!open[i][j]) {
return; // not an open site
}
if(full[i][j]) {
return; // already marked as full
}
// mark i-j as full
full[i][j] = true;
flow(open, full, i + 1, j); // down
flow(open, full, i, j + 1); // right
flow(open, full, i, j - 1); // left
flow(open, full, i - 1, j); // up
}
// does the system percolate?
public static boolean percolates(final boolean[][] open) {
final int n = open.length;
final boolean[][] full = flow(open);
for(int j = 0; j < n; j++) {
if(full[n - 1][j]) {
System.out.println("percolates");
return true;
}
}
System.out.println("does not percolate");
return false;
}
public static void print(final boolean[][] grid) {
final int m = grid.length;
final int n = grid[0].length;
System.out.println(m + " " + n);
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j]) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println("");
}
}
public static void main(String[] args) {
final boolean[][] open = readOpenFromFile();
print(flow(open));
System.out.println(percolates(open));
}
}
It can be seen that this program works by grabbing input from the file.txt file. However, how could I modify this code so as to request require a file name (perhaps at the command-line) each time the program is run, and use that as input?
I would think to add a String as an argument, then change that String into a file name. But this is easier said than done. Suggestions?
You can take it as an argument and modify code to -
public static void main(String[] args) {
// args[0] - Full path of the file
final boolean[][] open = readOpenFromFile(args[0]);
print(flow(open));
System.out.println(percolates(open));
}
public static boolean[][] readOpenFromFile(String filepath) {
final File f = new File(filepath);
try {
scan = new Scanner(f);
}
catch(FileNotFoundException ex) {
System.exit(0);
}
final int m = scan.nextInt();
final int n = scan.nextInt();
final boolean[][] grid = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
grid[i][j] = readBoolean();
}
}
return grid;
}
You can use this code:
public static boolean[][] readOpenFromFile(String file) {
final File f = new File( file );
// same code ...
}
public static void main(String[] args) {
if(args != null && args.length == 1) {
String file = args[0];
final boolean[][] open = readOpenFromFile(file);
print(flow(open));
System.out.println(percolates(open));
}
}
You need something like this, but you have to add checking file name:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
Link to site where you can find it

Categories

Resources