I want to have a method that returns the value that is presentend in the while loop. My code represents the reading of a txt file, where I read line by line and my goal is to return everytime it founds a line but is is showing me the same number over and over.
public String getInputsTxtFromConsole() {
String line = "";
//read inputs file
try {
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
}
} catch (FileNotFoundException e) {
}
return "";
}
As Nick A has said the use of return has, in this context two uses: return the value of a function and exit the function. I you need all the values as the are generated you can, for example,
Call a method that consume the new value:
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
ConsumerMethod(line);
}
Store in a global var like ArrayList, String[],...
Print it System.out.println(line).
...
But you cannot return a value and expect that the function continues working.
As I mentioned, pass the same scanner as a parameter to a method that reads a line and returns the line. You may want to define how it responds once there are no remaining lines.
public String getInputsTxtFromConsole(Scanner scanner) {
try {
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
} catch (FileNotFoundException e) {
}
return null;
}
I would also recommend using a different class to read from a file. BufferedReader would be a better approach.
BufferedReader in = new BufferedReader(new FileReader (file));
... // in your method
return in.readLine(); //return null if the end of the stream has been reached
Related
So I have this method here that should return the amount of lines in a csv file. Pretty simple right? Thing is instead of returning the amount of lines in the csv file(in this case 15) it returns 66. I honestly have know Idea why this would happen. I checked the csv file and verified that it is indeed 15 lines long with no empty lines. Also does anyone know why my Jpanes wont display without those three lines commented lines, my ide says the variables aren't in use anywhere.
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
Use BufferedReader instead of Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}
I'm in a beginning programming class, and seem to be having a major issue with searching a text file. What my code should do, based on the assignment:
Accept input, in this case a name and place that input into a .txt file
Allow the user to search for a name, or part of a name, and return all lines with matching text.
I have the input portion of the assignment complete, and am on the verge on completing the retrieval portion, but my code only searches the first line of the .txt file. I am able to print out all lines of the .txt file, and if I search for the name in Line 1 of the .txt file, it will print the line correctly. My issue comes when I am searching for a name that is not on Line 1. Below is my code:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
I have tried expanding the while (inFile.hasNextLine()) loop to include the second "if" statement, however that creates an issue for the "all names" search - it returns the entire list multiple times (however many lines are in the file). I have even tried creating another while (inFile.hasNextLine()) loop within the second "if" statement, and there is no difference in outcome.
I'm so frustrated at this point, because I've been working on this code for over a week, and have reviewed all of my notes and lecture recordings for this assignment with no help. Any insight would be much appreciated.
You are reading only 1 line of the file
String line = bufferedReader.readLine();
Why don't you read all lines and store them in a List;
List<String> lines = new ArrayList<>();
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
Then to print all lines containing a substring ignorecase:
lines.stream().filter(l -> l.toLowerCase().contains(search_term.toLowerCase))
.forEach(s -> System.out.println(s));
You need to loop the readLine()
For example:
File f = new File(ruta);
if(!f.exists()) //Error
else {
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
//line = the next line
}
}
I am trying to replace ? with - in my text document but just the ArrayList<String> is being written in the new file without all lines of the old one. How can I fix that?
File file = new File("D:\\hl_sv\\L09MF.txt");
ArrayList<String> lns = new ArrayList<String>();
Scanner scanner;
try {
scanner = new Scanner(file);
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
// System.out.println("I found it on line " + lineNum);
}
}
lines.clear();
lines = lns;
System.out.println("Test: " + lines);
FileWriter writer;
try {
writer = new FileWriter("D:\\hl_sv\\L09MF2.txt");
for (String str : lines) {
writer.write(str);
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't understand why you're storing the lines in a List to begin with. I would perform the transform and print while I read. You don't need to test for the presence of the ? (replace won't alter anything if it isn't present). And, I would also use a try-with-resources. Something like
File file = new File("D:\\hl_sv\\L09MF.txt");
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\L09MF2.txt");
Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
writer.println(line.replace('?', '-'));
}
} catch (Exception e) {
e.printStackTrace();
}
Examine this code:
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
}
You are only adding the current line (with the replacement) if it had a ? in it, ignoring other lines. Restructure it to always add the existing line.
if (line.contains("?")) {
line = line.replace("?", "-");
}
lns.add(line);
Additionally, the part
if (line.contains("?"))
scans line to look for a ?, and then the code
line.replace("?", "-");
does the same thing, but this time also replacing any ? with -. You may as well scan line just once:
lns.add(line.replace("?", "-"));
Note that creating an ArrayList just to hold the new lines wastes a fair amount of memory if the file is large. A better pattern would be to write each line, modified if necessary, right after you read in the corresponding line.
Within your while loop you have an if statement checking the line which adds the altered line to the array. You also need to add the unaltered lines to the array.
This should fix your issue:
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
// System.out.println("I found it on line " + lineNum);
}
else{
lns.add(line);
}
Previously, you were only adding the line to your ArrayList if it contained a "?" character. You need to add the line to the ArrayList whether or not it contains "?"
I would use a different approach if I'm trying to work on the functionality you want to implement, please check this approach and tell me if this helps you :)
public void saveReplacedFile() {
//1. Given a file in your system
File file = new File("D:\\hl_sv\\L09MF.txt");
try {
//2. I will read it, not necessarily with Scanner, but use a BufferedReader instead
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
//3. Define a variable that will hold the value of each line
String line = null;
//and also the information of your file
StringBuilder contentHolder = new StringBuilder();
//why not get your line separator based on your O.S?
String lineSeparator = System.getProperty("line.separator");
//4. Check your file line by line
while ((line = bufferedReader.readLine()) != null) {
contentHolder.append(line);
contentHolder.append(lineSeparator);
}
//5. By this point, your contentHolder will contain all the data of your text
//But it is still a StringBuilder type object, why not convert it to a String?
String contentAsString = contentHolder.toString();
//6. Now we can replace your "?" with "-"
String replacedString = contentAsString.replace("?", "-");
//7. Now, let's save it in a new file using BufferedWriter :)
File fileToBeSaved = new File("D:\\hl_sv\\L09MF2.txt");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileToBeSaved));
bufferedWriter.write(replacedString);
//Done :)
} catch (FileNotFoundException e) {
// Exception thrown if the file does not exist in your system
e.printStackTrace();
} catch (IOException e) {
// Exception thrown due to an issue with IO
e.printStackTrace();
}
}
Hope this is helpful. Happy coding :)
If you can use Java 8 then your code can be simplified to
try (PrintStream ps = new PrintStream("D:\\hl_sv\\L09MF2.txt");
Stream<String> stream = Files.lines(Paths.get("D:\\hl_sv\\L09MF.txt"))) {
stream.map(line -> line.replace('?', '-')).forEach(ps::println);
} catch (IOException e) {
e.printStackTrace();
}
I am designing a program that will load a text file into different media file classes (Media > Audio > mp3, Media > Video > Avi, etc).
Now the first line of my text file is how many files there are in total, as in
3
exmaple.mp3,fawg,gseges
test.gif,wfwa,rgeg
ayylmao.avi,awf,gesg
Now that is what is in my text file, I want to first get the first line separately, then loop through the rest of the files.
Now I understand I can simply count how many files are in by using an int that grows as I loop but I want it clear in the file aswell, and I'm not sure how to go about this.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while(line != null)
{
//Get the first line of the text file seperatly? (Then maybe remove it? idk)
//Split string, create a temp media file and add it to a list for the rest of the lines
}
//String[] split = s.next().split(",");
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
I hope my question is clear, if it TL;DR I want to get the first line of a text file separately, then the rest Id like to loop through.
I wouldn't advice using a for-loop here, since the file might contain additional lines (e.g. comments or blank lines) to make it more human-readable. By examining the content of each line, you can make your processing more robust against this sort of thing.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
String line = reader.readLine(); // <-- Get the first line. You could consider reader as a queue (sort-of), where readLine() dequeues the first element in the reader queue.
int numberOfItems = Integer.valueOf(line); // <-- Create an int of that line.
// Do the rest:
while((line = reader.readLine()) != null) // <-- Each call to reader.readLine() will get the next line in the buffer, so the first time around this will give you the second line, etc. until there are no lines left to read.
{
// You will not get the header here, only the rest.
if(!line.isEmpty() || line.startsWith("#") {
// If the line is not empty and doesn't start with a comment character (I chose # here).
String[] split = line.split(",");
String fileName = split[0];
// etc...
}
}
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
You don't need while loop to read up to end of file. Read first line and convert it to int than loop through.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
int lineNo=Integer.parseInt(reader.readLine());
// Now read upto lineNo
for(int i=0; i < lineNo; i++){
//Do what you need with other lines.
String[] values = reader.readLine().split(",");
}
} catch (Exception e) {
//Your exception handling goes here
}
}
I have an assignment stating that "You can assume that input will come from standard input in a stream. You may assume that the markers have access to all standard libraries".
How do I go about reading several lines/inputs and saving all the inputs as one string and then outputting that string from a function?
Currently this is my function, but it's not working properly, at one stage it wasn't reading more than one line and now it doesn't work at all.
public static String readFromStandardIO() {
String returnValue = "";
String newLine = System.getProperty("line.separator");
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
System.out.println("Enter text...\n");
while (!(reader.readLine() == reader.readLine().trim())) {
userInput = reader.readLine();
returnValue += userInput;
}
System.out.println("You entered : " + returnValue);
return returnValue;
} catch (Exception e) {
}
return null;
}
Thank you for the assistance!
The problem is you're calling reader.readLine() three different times, so you'll end up comparing two completely different strings and then recording yet another one.
Also, it's generally frowned upon to compare strings using == (as comparing Objects with == asks if they are the same actual object (yes, Java's forgiving in that regard with strings, but it's still frowned upon)).
You'll need to do something more akin to:
public static String readFromStandardIO() {
String returnValue = "";
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Enter text...\n");
while (true) {
userInput = reader.readLine();
System.out.println("Finally got in here");
System.out.println(userInput);
returnValue += userInput;
if (!userInput.equals(userInput.trim())) {
break;
}
}
System.out.println("You entered : " + returnValue);
} catch (Exception e) {
}
return returnValue;
}