I have a file in the same folder of the main class called edges, but when i run it, it said there is an error.
Exception in thread "main" java.io.FileNotFoundException:
What should i change for the program?
import graphs.arrayGraph;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
class underground
{
static int N = 308;
static double [][] edges = new double [N][N];
static String [] stationNames = new String[N];
static ArrayList<String> convert (ArrayList<Integer> m)
{
ArrayList<String> z = new ArrayList<String> ();
for (Integer i:m) z.add(stationNames[i]);
return z;
}
static HashSet<ArrayList<String>> convert (HashSet<ArrayList<Integer>> paths)
{
HashSet <ArrayList <String>> k = new HashSet <ArrayList <String>> ();
for (ArrayList <Integer> p:paths) k.add(convert(p));
return k;
}
public static void main (String[] args) throws Exception
{
for(int i=0; i<N; i++) for (int j=0; j<N; j++) edges[i][j]=0.0;
URL url= underground.class.getResource("edges");
Scanner s = new Scanner (new FileReader(url.getPath()));
String z = s.nextLine();
while (s.hasNext())
{
z = s.nextLine();
String[] results = z.split(",");
edges[Integer.parseInt(results[0])] [Integer.parseInt(results[1])]= 1.0;
edges[Integer.parseInt(results[1])] [Integer.parseInt(results[0])]= 1.0;
}
url= underground.class.getResource("stations");
s = new Scanner(new FileReader(url.getPath()));
z = s.nextLine();
while (s.hasNext())
{
z = s.nextLine();
String[] results = z.split(",");
stationNames[Integer.parseInt(results[0])] = results[3];
}
arrayGraph G = new arrayGraph (edges);
System.out.println(convert(G.shortestPaths(Integer.parseInt(args[0]),Integer.parseInt(args[1]))));
}
}
You have to include the file extension too. Sometimes that may be a problem.
Try edges.txt or whatever the extension is.
Pass an InputStream into the Scanner. Don't use a FileReader.
i.e., change this:
URL url= underground.class.getResource("edges"); // are you sure the name is correct?
Scanner s = new Scanner (new FileReader(url.getPath()));
to this:
InputStream is = underground.class.getResourceAsStream("edges");
Scanner s = new Scanner(is);
Related
I am trying to write a java program that reads a text file and counts the number of times each word occurs. But I keep getting the No such element Exception. I assume there is something wrong with the ArrayList or how I am accessing the elements of it. Any help would be appreciated.
package text_analyzer;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Text_analyzer
{
public static void main(String[] args) throws Exception
{
File file = new File("TestFile.txt");
Scanner sc = new Scanner(file);
int i = 0, indexOfWord = 0, count = 0;
List<String> words = new ArrayList<String>();
List<Integer> wordCount = new ArrayList<Integer>();
while (sc.hasNextLine())
{
String word = sc.next();
if(words.contains(word))
{
indexOfWord = words.indexOf(word);
count = wordCount.get(indexOfWord);
count = count+1;
wordCount.add(indexOfWord, count);
}
else
{
words.add(i,word);
wordCount.add(i,1);
i++;
}
}
sc.close();
int no_of_elements = words.size();
for(int j = 0; j < no_of_elements; j++)
System.out.println(words.get(j));
}
}
Your logic is correct;
Check the path of the file, and make sure it is present or add an additional check in code.
File Path
Add exception handling for new File() method in case file is not found.
File file = new File("C:\\work\\TestFile.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Result: Output result
So I have to extract data from a text file.
The text file is set up like this.
3400 Moderate
310 Light
etc.
I need to extract the numbers, store them in one array, and the strings, and store them in another array so I can do calculations to the numbers based on whats written in the array, and then output that to a file. I've got the last part down, I just cant figure out how to separate the ints from the strings when I extract the data from the txt. file.
Here is what I have now, but it's just extracting the int and the word as a String.
import java.io.*;
import java.util.*;
public class HorseFeed {
public static void main(String[] args){
Scanner sc = null;
try {
sc = new Scanner(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
for(int i = 0; i< 100; i++){
System.out.print(arr[i]);
}
}
}
Use split(String regex) in String class. Set the regex to search for whitespaces OR digits. It will return a String[] which contains words.
If you are analyzing it line by line, you would want another String[] in which you would append all the words from the new lines.
plz, follow the code.
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HorseFeed {
public static void main(String[] args) throws FileNotFoundException, IOException {
List<String> lineList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt")));
String line;
while ((line = br.readLine()) != null) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(line);
if( pattern.matcher(line).matches()){
while(matcher.find()){
lineList.add(matcher.group());
}
}
}
}
}
here lineList contains your integer.
This should work:
import java.io.*;
import java.util.*;
public class HorseFeed {
public static void main(String[] args) throws FileNotFoundException {
List<Integer> intList = new ArrayList<Integer>();
List<String> strList = new ArrayList<String>();
Scanner sc = new Scanner(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt"));
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lineParts = line.split("\\s+");
Integer intValue = Integer.parseInt(lineParts[0]);
String strValue = lineParts[1];
intList.add(intValue);
strList.add(strValue);
}
System.out.println("Values: ");
for(int i = 0; i < intList.size(); i++) {
System.out.print("\t" + intList.get(i) + ": " + strList.get(i));
}
}
}
First extract all text of file and stored it into String . then use replaceall method of string class with pattern to remove digits from it.
Example:
String fileText = new String("welcome 2 java");
ss = fileText.replaceAll("-?\\d+", "");
System.out.println(ss);
I am writing code that reads in a text file through the command line arguments in the main method and prints out each word in it on its own line without printing any word more than once, it will not print anything, can anyone help?
import java.util.*;
import java.io.*;
public class Tokenization {
public static void main(String[] args) throws Exception{
String x = "";
String y = "";
File file = new File(args[0]);
Scanner s = new Scanner(file);
String [] words = null;
while (s.hasNext()){
x = s.nextLine();
}
words = x.split("\\p{Punct}");
String [] moreWords = null;
for (int i = 0; i < words.length;i++){
y = y + " " + words[i];
}
moreWords = y.split("\\s+");
String [] unique = unique(moreWords);
for (int i = 0;i<unique.length;i++){
System.out.println(unique[i]);
}
s.close();
}
public static String[] unique (String [] s) {
String [] uniques = new String[s.length];
for (int i = 0; i < s.length;i++){
for(int j = i + 1; j < s.length;j++){
if (!s[i].equalsIgnoreCase(s[j])){
uniques[i] = s[i];
}
}
}
return uniques;
}
}
You have several problems:
you're reading whole file line by line, but assign only last line to variable x
you're doing 2 splits, both on regexp, it is enough 1
in unique - you're filling only some parts of array, other parts are null
Here is shorter version of what you need:
import java.io.File;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Tokenization {
public static void main(String[] args) throws Exception {
Set<String> words = new HashSet<String>();
try {
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String[] lineWords = scanner.nextLine().split("[\\p{Punct}\\s]+");
for (String s : lineWords)
words.add(s.toLowerCase());
}
scanner.close();
} catch (Exception e) {
System.out.println("Cannot read file [" + e.getMessage() + "]");
System.exit(1);
}
for (String s : words)
System.out.println(s);
}
}
I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.
Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextDouble())
{
salesData.add(salesDataFile.nextDouble());
}
salesDataFile.close();
System.out.println(salesData);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
}
salesDataFile.close();
System.out.println(salesData);
}
}
Read lines from file, then for each file get doubles using Scanner.
And for per line basis, you can just create Lists for every line, like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
System.out.println(salesData);
}
salesDataFile.close();
}
}
As you are getting per line values inside first while() loop, you can do whatever with line.
// number of values in file
int totalNumValues = 0;
// total sum
double totalSum = 0;
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
// total values in this line
int numValuesInLine = 0;
// sum in this line
double sumLine = 0;
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
double value = scanner.nextDouble();
sumLine = sumLine + value;
numValuesInLine++;
totalNumValues++;
totalSum = totalSum + value;
}
scanner.close();
System.out.println(salesData);
}
I'd do something like this:
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<ArrayList< double > > salesData = new ArrayList<>();
while(salesDataFile.hasNextLine() )
{
String stringOfNumbers[] = salesDataFile.nextLine().split(",");
ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
for( int i = 0; i < stringOfNumbers.length; ++i )
aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
//... Perform your row calculations ...
salesData.add( aux );
}
salesDataFile.close();
System.out.println(salesData);
As #Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.
This is what you are looking for,
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileRead {
public static void main(String args[])
{
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Double> saleNumbers= new ArrayList<Double>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Add number from file to list
saleNumbers.add( parseDecimal(strLine));
}
//Close the input stream
in.close();
System.out.println(saleNumbers);
}catch (Exception e){
e.printStackTrace();
}
}
public static double parseDecimal(String input) throws NullPointerException, ParseException{
if(input == null){
throw new NullPointerException();
}
input = input.trim();
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
ParsePosition parsePosition = new ParsePosition(0);
Number number = numberFormat.parse(input, parsePosition);
if(parsePosition.getIndex() != input.length()){
throw new ParseException("Invalid input", parsePosition.getIndex());
}
return number.doubleValue();
}
}