I'm just starting out in java and I'm trying to make a greedy algorithm. The first step is to read the file.txt with the jewel values and bag weight limit and such. unfortunately I am having trouble getting the program to run. I am using eclipse and when I click run I get the following error message "the selection cannot be launched, and there are no recent launches".
When I select the java greedy algorithm folder in the file tree and select run i get the following message "selection does not contain a main type". the work file and file.txt are saved in the same folder on my desktop but I wonder if the program isn't finding it. here's my code:
/** open and read a file, and return the lines in the file as a list of strings */
private List<String> readFile(file.txt)
{
List<String> records = new ArrayList<String>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(file.txt));
String line;
while (( line = reader.readLine()) != null)
{
records.add(line);
}
reader.close():
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", file.txt);
e.printStackTrace();
return null;
}
}
Thanks for the help.
You have to add a method named void main(String[] args).
This is the method that gets called when you start your program.
In this main method you can call your readFile method, like so:
public static void main(String[] args) {
readFile();
}
A java class should have a main method then only you can run that.
So, your class will be like this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String... args) {
//call readFile
List<String> someList = readFile(<pass filename here>);
//do something here with someList
}
/** open and read a file, and return the lines in the file as a list of strings */
private static List<String> readFile(String filename)
{
List<String> records = new ArrayList<>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while (( line = reader.readLine()) != null)
{
records.add(line);
}
reader.close();
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.",filename );
e.printStackTrace();
return null;
}
}
}
Note that, I marked readFile method as static which is because I am invoking it from main method without creating an instance of Test class. If you create an instance of Test class, and call readFile method on it, then you can remove static modifier.
You are missing the
public static void main(String args[])
{
...
}
There you can call your function.
Related
I'm trying to read a text file called "text.txt" and then remove the punctuation in that file however I need some help. The first code below is the file reading portion, I'm trying to just remove the punctuation. The second code is me trying to remove it but it didn't work. Help??
public class file {
public static void main(String[] args) {
try {
File file = new File("text.txt");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
}
}
}
String line;
String processedLine="";
while ((line = in.readLine()) != null) {
processedLine = line.replaceAll("!~`##$%^&*()-_=+'><:;?","");
}
I tried to hardcode all the punctuation away but it didn’t work.
I posted a comment earlier with a typo in it, so I thought I'd correct it with working code below:
import java.nio.file.Files;
import java.nio.file.Paths;
public class PunctuationFilter {
public static void main(String[] args) {
try {
Files.lines(Paths.get(args[0]))
.map(s -> s.replaceAll("\\p{Punct}", ""))
.forEach(System.out::println);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
I'm new to java and I'm having a little problem with my code. There's no error and such, it just keeps saying process finished but no output was displayed. The filename is correct as I've checked.
import java.nio.file.;
import java.io.;
public class GuessingGame {
public GuessingGame() {
String filename = "C:\\Users\\angela\\Documents\\words.txt";
Path path = Paths.get(filename.toString());
try {
InputStream input = Files.newInputStream(path);
BufferedReader read = new BufferedReader(new InputStreamReader(input));
String word = null;
while((word = read.readLine()) !=null) {
System.out.println(word);
}
}
catch(IOException ex) {
}
}
public static void main (String[] args) {
new GuessingGame();
}
}
You are ignoring the exception and you don't close the file. Save some typing by using the built-in input.transferTo() for copying the file to System.out, and pass on the exception for the caller to handle by adding throws IOException to constructor and main.
Replace your try-catch block with this try-with-resources, which handles closing the file after use:
try (InputStream input = Files.newInputStream(path)) {
input.transferTo(System.out) ;
}
You managed to call the intended class, but you also needed to specify the specific function which you have declared in the function. Like so:
public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }
I have a private method called from the main() method to which I am passing the input file path as an argument. My code-under-test is the main() method. Somewhere in the middle of the private method, the file is read and some operations performed.
How can I:
1. Pass the file path of String type ("src/test/resources/test.txt") as an argument. I am getting FileNotFoundException if I pass the file path.
2. How can I test an IOException that is handled in private method on not finding the file?
Adding my code snippets here:
Code under Test:
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile(args);
}
private void readFile(String[] args) {
if (args != null) {
String file = args[0];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Test for main:
#Test
void mainTest() {
String[] args = {"/test_input.txt"};
MyApp.main(args);
assertNotNull(<some_object_after_processing>);
}
To get file path you can use suitable way mentation in this link
There is no need to check any assertion for main method.
If the test case is completed successfully then it passed.
Thank you for raising your queries! First, you need to change your application code because you are reading a single file from the args[0] position then why you are going to read the strings array [File Array or collection of files].
1] Create 'resources' folder in your project:
Right-click on project and create a folder with name 'resources'.
2] Create 'test.txt' into the 'resources' folder.
3] Modified code:
package com.application;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile("resources/Test.txt");
}
private void readFile(String fileName) {
if (fileName != null) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Here, You can pass a fileName directly to the method. I hope that it will help you to resolve your first query.
I would like to know how to write all lines from the java output in a .txt file.
I've done some tests so far but I don't seem to be able to find the solution :/
Here is a small code, if you could show me with this one, it would be greatly appreciated :
The code shown below asks the user what to write in a .txt file but I want it to write all the printed lines in a .txt file without asking the user anything. Thank you
package test;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Test {
public static void main(String[] args)throws Exception {
System.out.println("Hello");
System.out.println("Hi");
System.out.println("Hola");
System.out.println("Bonjour");
System.out.println("Hallo");
System.out.println("Hej");
System.out.println("Alo");
System.out.println("Ciao");
writeOutput();
}
public static void writeOutput() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromInput = in.readLine();
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println(lineFromInput);
out.close();
}
}
Use directly PrintStream to write the String values.
public static void main(String[] args)throws Exception {
PrintStream printStream = new PrintStream(new File("output.txt"));
// hook for closing the stream
Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
// writing
write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
"Alo","Ciao");
// writing again
write(printStream, "A new String", "And again another one...");
}
public static void write(PrintStream printStream, String... values) throws Exception {
try{
for (String value : values){
printStream.println(value);
}
printStream.flush();
}
catch (Exception e){
// handling exception
}
}
}
java test.Test > somefile.txt
A Java program on CodeEval had to accept a file path as an argument. I used a command line argument to do this, but I get an exception as below when I submitted my code on CodeEval. What are some potential solutions to this problem?
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at java.util.StringTokenizer.nextElement(StringTokenizer.java:407)
at Main.FileRead(Main.java:61)
at Main.main(Main.java:26)
Here's the boilerplate Java code that I use for my Codeeval code. The specific problem code generally goes in the processLine method. I don't use Scanner or StringTokenizer. I use the String split method to process the input.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main implements Runnable {
private String fileName;
public Main (String fileName) {
this.fileName = fileName;
}
#Override
public void run() {
try {
processFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processFile() throws IOException {
BufferedReader br = new BufferedReader(
new FileReader(fileName));
String line = "";
while ((line = br.readLine()) != null) {
processLine(line);
}
br.close();
}
private void processLine(String line) {
System.out.println(line);
}
public static void main(String[] args) {
new Main(args[0]).run();
}
}
Firstly, Check the name of class.Class name should be 'Main'.
Second you have to give all the imports in CodeEval Editor which you are using in your program.
This happens if you don't check to see if there are any more tokens (by calling hasMoreTokens). If no more tokens exist and you call nextToken, you will get this exception. However, without seeing the rest of your code, there is no way to know what is actually happening.