Im trying to a specific String of number in a csv file and I keep getting an a FileNotFound exception even though the files exists. I cant seem to fix the problem
Sample Csv file
12141895, LM051
12148963, Lm402
12418954, Lm876
User Input : 12141895
Desired Result : True
import javax.swing.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.List;
public class tester
{
public static void main (String [] args ) throws IOException
{
boolean cool = checkValidID();
System.out.println(cool);
}
public static boolean checkValidID() throws IOException
{
boolean results = false;
Scanner scan = new Scanner(new File("C:\\Users\\Packard Bell\\Desktop\\ProjectOOD\\IDandCourse.csv"));
String s;
int indexfound=-1;
String words[] = new String[500];
String word = JOptionPane.showInputDialog("Enter your student ID");
while (scan.hasNextLine())
{
s = scan.nextLine();
if(s.indexOf(word)>-1)
indexfound++;
}
if (indexfound>-1)
{
results = true;
}
else
{
results = true;
}
return results;
}
}
use:
import java.io.File;
import java.io.FileNotFoundException;
Also, in your function declaration try using
public static boolean checkValidID() throws FileNotFoundException
and likewise with the main function.
If the file is present and named correctly, this should handle it.
Related
I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)
Essentially I need to create a anagram program to filter out the specific characters I input using a scanner from a dictionary file. Example, if I enter 'Stop' the result would be "tops spot pots" etc
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.stream.Stream;
public class Anagram1 {
public static void main(String[] args) throws IOException {
new Anagram1().doIt();
}
private void doIt() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
String theWord = scanner.next();
if (theWord.equals("999")) {
scanner.close();
break;
}
ISinglyLinkedList<String> anagrams = listAnagrams(theWord);
anagrams.forEach(System.out::print);
}
}
private ISinglyLinkedList<String> listAnagrams(final String theWord) throws
IOException {
Stream<String> dict = Files.lines(Paths.get("Data", "pocket.dic"));
ISinglyLinkedList<String> theList = dict
.collect(Util.toSinglyLinkedList())
//Add a filter and a forEach to print the specific words you wanna print
;
dict.close();
return theList;
}
}
So far the program only gives me enter code here every single word in the dictionary. Is there a way to filter out only the words that share the same letter?
You could use the fact that two words are anagrams if after sorting they are the same:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Anagram1 {
public static void main(String[] args) throws IOException {
Map<String, List<String>> anagramsMap = new HashMap<>();
try (Stream<String> dict = Files.lines(Paths.get("Data", "pocket.dic"))) {
dict.forEach(w -> anagramsMap.computeIfAbsent(getSortedWord(w), x -> new ArrayList<>()).add(w));
}
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a word to get its anagrams or 999 to exit: ");
String word = scanner.next();
if (word.equals("999")) {
break;
}
List<String> anagrams = anagramsMap.get(getSortedWord(word.toLowerCase()));
System.out.println(String.join(" ", anagrams));
}
}
public static String getSortedWord(String word) {
return Stream.of(word.split("")).sorted().collect(Collectors.joining());
}
}
Example Usage:
Enter a word to get its anagrams or 999 to exit: Stop
post pots spot stop tops
Enter a word to get its anagrams or 999 to exit: 999
So I'm relatively new to java and I'm trying to use a method from a different class inside my main.
The method I'm using to pull doesn't contain any data initially but pulls the data from a text doc.
I've included the code that calls the other class method that loads the data from the file. It sill doesn`t work, so where is my mistake?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
//output of animalList class here
}
Here is the class I'm trying to pull from:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public void animalDetails () {
int i = 0;
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
StringBuilder animalDetailList = new StringBuilder();
String line;
while ((line = animalList.readLine()) != null) {
for (i = 0; i <4 ; i++) {
System.out.println(line);
animalList.readLine();
}
}
animalReader.close();
System.out.println(animalDetailList.toString());
}
catch (IOException e) {
}
}
}
So I want to have the output of the animalList class in my main, but I don't know how to bring it over because I'm not necessarily bring over variable, but a process. The full thing should bring the first line and four past it (so a total of the first five lines in the doc). Hopefully that makes things easier to see my problem.
This is a mcve of AnimalList :
public class AnimalList {//use java naming convention
public void animalDetails () {
//mcve should be runnable. The problem you ask help with is not
//reading from file, so remove file reading functionality to make it mcve
StringBuilder animalDetailList = new StringBuilder();
animalDetailList.append("Family: Cats").append("\n")
.append("Type : Panther").append("\n")
.append("Weight: 250kg").append("\n")
.append("Color : Pink");
System.out.println(animalDetailList.toString());
}
}
Invoke its method from another class:
public class FinalRobert {
public static void main(String[] args) {
//to invoke animalDetails() method use
AnimalList aList = new AnimalList();
aList.animalDetails();
//if you do not need the aList refrence you could use
//new AnimalList().animalDetails();
}
}
Output
Family: Cats Type : Panther Weight: 250kg Color :
Pink
I hope this might help you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
animalList list = new animalList();
list.animalDetails();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public String animalDetails () {
int i = 0;
String output="";
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
String line;
while ((line = animalList.readLine()) != null & i<4) {
System.out.println(line);
output = output + "\n"+ line;
i++;
}
animalReader.close();
System.out.println(output);
}
catch (IOException e) {
}
return output;
}
}
I'm working on resume parser and i can get some of data i.e company details from text but not getting if it is kept in a grid or table
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class CmpnyNameex {
public static void main(String[] args)throws IOException {
String text="";
String name="";
XWPFDocument msDocx = new XWPFDocument(new FileInputStream("A:\\Resumes\\Anwesh.docx"));
XWPFWordExtractor extractor = new XWPFWordExtractor(msDocx);
text = extractor.getText();
}
catch(FileNotFoundException ex){ex.printStackTrace();
JOptionPane.showMessageDialog(null,"The system cannot find the file specified file it may be because of old file format","Error",JOptionPane.ERROR_MESSAGE);
}
String rx13="(?<=Have been associated with).*.(.*Ltd?)";
Pattern p1 = Pattern.compile(rx13);
Matcher found1 = p1.matcher(text);
while(found1.find())
{
name= found1.group(0);
}
}
}
i had a notepad file with
tea--10.00
coffee--20.00
bread--30.00.how to seperate tea,coffee,bread strings to an arrayList and seperate ineger values and storing to another variables.i need to program in java.i programmed like this
package sample_god1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class filedata_retive_seperateVlaues
{
public static void main(String[] args) throws IOException
{
int var;
String var2;
Scanner sc=new Scanner(new File("222.txt"));
while(sc.hasNextLine())
{
String[] mnu=sc.nextLine().split("--");
int[] nums=new int[mnu.length];
for(int i=0;i<nums.length;i++)
{
System.out.println(var[i]);
}
}
}
}
List<String> items = new ArrayList<>();
List<Double> prices = new ArrayList<>();
while(sc.hasNextLine())
{
String[] mnu=sc.nextLine().split("--");
int[] nums=new int[mnu.length];
for(int i=0;i<nums.length;i++)
{
items.add(mnu[0]);
prices.add(Double.parseDouble(mnu[1]));
}
}
Instead of two separate list you should have a map ,
map.put(mnu[0],Double.parseDouble(mnu[1]));