I have a text file that contains three lines of code.
That is,
Hello.
How may I help you?
What can I do for you today?
I tried printing the first line and it worked.Now I want to print the rest of the lines in the console but it's only displaying first line 4 times like this.
Hello.
Hello.
Hello.
Hello.
Below is the code that I am trying to run and the file is in root folder.
public class Test
{
public static void main(String[] args)
{
int counter = 0;
/*open the file */
BufferedReader reader = null;
String greeting = null;
int rand;
File file = new File("Greetings.txt");
try
{
reader = new BufferedReader(new FileReader(file));
/*read the file*/
String greetingPicker = null;
/*single greeting*/
/*greeting = greetingPicker;*/
List<String> listOfGreetings = new ArrayList<String>();
while ((greetingPicker = reader.readLine()) != null)
{
listOfGreetings.add(greetingPicker);
}
reader.close();
rand = (int) Math.random() * (listOfGreetings.size()) + 1;
greeting = listOfGreetings.get(rand - 1);
for (int i = 0; i < listOfGreetings.size(); i++)
{
System.out.println(listOfGreetings.get(counter));
}
} catch (Exception e)
{
System.out.println("File cannot be found!!");
}
}
}
You are getting the value for the wrong index: You mistakenly used counter instead of i in your loop. Change this
for(int i=0; i < listOfGreetings.size(); i++){
System.out.println(listOfGreetings.get(counter));
}
to this:
for(int i=0; i < listOfGreetings.size(); i++){
System.out.println(listOfGreetings.get(i));
}
By the way, you are using Math.random() and it is instantly converted to a int, because you forgot to add correct parentheses, so change this
rand = (int) Math.random() * (listOfGreetings.size()) + 1;
to this:
rand = (int) (Math.random() * (listOfGreetings.size()) + 1);
You dont need your counter, use i ! ;)
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
Just change
System.out.println(listOfGreetings.get(counter));
by
System.out.println(listOfGreetings.get(i));
You forgot to change the counter.
You don't need to use counter, and put close in the end like this:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
reader.close();
The "counter" variable here is not being incremented:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(counter));
}
You should change it to "i" instead:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
Try using the chunk below. It's simpler and works perfectly.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileReader{
public static void main(String[] args){
//define file path
String stringFileToRead = "Greetings.txt";
//the file
File stringFile = new File(stringFileToRead);
//Scanner object to take input from the file
Scanner fileToRead = null;
try{
//Read the file
fileToRead = new Scanner(stringFile);
}
//catch exception
catch (Exception e){
System.out.println("Unable to open file.");
System.exit(0);
}
//print the content of the file
System.out.println("The file contains the following contents:\n");
int lineNum = 1;
while(fileToRead.hasNextLine()){
String line = fileToRead.nextLine();
System.out.println("Line "+lineNum+": "+line);
lineNum++;
}
}
}
Related
i have a java code where i read a txt file, then iterate it so that i can fill it in a 2d array.
after i read the file i was able to print out its contents so i was sure that the file was read. and i was also sure that the bufferedreader library's .hasNextLine method was showing true when a line was found.
but when i used it in a while loop, it just acted as if no lines where found, thus it didnt iterate, hense i couldn't know how many rows i had in the table.==>
while (sc.hasNextLine()==true){ row++;}
furthermore, when i hard-coded the number of rows so that i could check if everything else was ok, i got a line not found error. please help me out.
i will link the code below.
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void
main(String args[]) throws Exception {
int row=0;
int column=0;
int count=0;
BufferedReader x = new BufferedReader(new FileReader("src\\Table.txt"));
Scanner sc = new Scanner(x);
System.out.println(sc.nextLine()+sc.hasNextLine()+"\n"+sc.nextLine()+sc.hasNext()+"\n"+sc.nextLine()+"\n"+sc.nextLine()+sc.hasNextLine());
while (sc.hasNextLine()==true){ row++;}
System.out.println(row);
for (int i=0; i<row; i++) {
String[] line = sc.nextLine().trim().split(",");
System.out.println(line);
for (String line1 : line) {
if (",".equals(line1)) {
count++;
}
count+=1;
if(count>column){
column=count;
}
}
}
String [][] myArray = new String[row][column];
for (int i=0; i<myArray.length; i++) {
String[] line = sc.nextLine().trim().split(",");
for (int j=0; j<line.length; j++) {
myArray[i][j]= line[j];
}
}
System.out.println(Arrays.deepToString(myArray));
}
}
i also get this output
"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.2\lib\idea_rt.jar=52205:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\acer pc\IdeaProjects\PDM\out\production\PDM" com.company.Main
CalculusII,Algebra,Networktrue
CalculusII,Algebra,Webtrue
CalculusIII,Prog2,Network
Algebra,Prog1,Webfalse
0
[]
Process finished with exit code 0
When you perform the following statement you've already read your entire file, so there are no lines left to read.
System.out.println(sc.nextLine()+sc.hasNextLine()+"\n"+sc.nextLine()+sc.hasNext()+"\n"+sc.nextLine()+"\n"+sc.nextLine()+sc.hasNextLine());
This is why your following iterations stop immediately and don't show the expected output. Maybe, what you were expecting was for the Scanner's internal cursor to reset itself once the end of file was reached. However, this is definitely not the behavior of the Scanner class (or any other), and none of its methods offer to reset or reposition the Scanner's cursor to a specific point of the file.
What you need to do is to close your connections and re-establish them in order to restart reading the content. For example, you could include every file consumption within a try block to automatically dispose every connection once you're done.
To simplify your code, in your first loop you could count the number of lines and check for the line with "the most columns", while in your second loop you could re-read the file's content.
public class Main {
public static void main(String args[]) {
int row = 0;
int column = 0;
int tmp = 0;
try (FileReader fr = new FileReader("src\\Table.txt");
BufferedReader br = (new BufferedReader(fr));
Scanner sc = new Scanner(br)) {
//First file consumption
while (sc.hasNextLine()) {
row++;
tmp = sc.nextLine().split(",").length;
if (tmp > column) {
column = tmp;
}
}
System.out.println(row);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
try (FileReader fr = new FileReader("src\\Table.txt");
BufferedReader br = (new BufferedReader(fr));
Scanner sc = new Scanner(br)) {
//Second file consumption
String[][] myArray = new String[row][column];
for (int i = 0; i < myArray.length; i++) {
String[] line = sc.nextLine().trim().split(",");
for (int j = 0; j < line.length; j++) {
myArray[i][j] = line[j];
}
}
System.out.println(Arrays.deepToString(myArray));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
i cannot for the life of me seem to take in the contents of this file, i keep getting No such elements exception on line 25, all help appreciate. heres a link to the file link
heres my code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class practiceFinal {
public static void main(String[] args) {
String fileName = args[0];
int length = fileLength(fileName);
int[] array = new int[length];
String[] list = new String[length];
arrayPopulate(array, list, fileName);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
}
public static int fileLength(String fileName) {
File file = new File(fileName);
Scanner fileScan = new Scanner(fileName);
int counter = 0;
while (fileScan.hasNext()) {
fileScan.next();
counter++;
}
return counter;
}
public static void arrayPopulate(int[] array, String[] list, String fileName) {
File file = new File(fileName);
Scanner fileScan = null;
try {
fileScan = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("details: " + e.getMessage());
}
for (int i = 0; i < array.length; i++) {
array[i] = fileScan.nextInt();
list[i] = fileScan.next();
}
}
}
There are a few problems here. First of all you are using fileScan.next(); to try and get the length of a file. This is going to give you 2 times the length because you are counting each token fileScan.next() grabs which will be first the number and then the letter.
Length of lines is 144 but when you calculate it, it returns 288.
So use fileScan.nextLine();, now some people have mentioned this but your program is still not going to work correctly because you passed Scanner fileScan = new Scanner(fileName); // mistake passed fileName instead of file
Here are the changes I made inside the fileLength() method:
File file = new File(fileName);
Scanner fileScan = new Scanner(file); // mistake passed fileName instead of file, changed from Scanner fileScan = new Scanner(fileName)
while (fileScan.hasNextLine()) {
fileScan.nextLine(); // changed from fileScan.next()
counter++;
}
Your output looks like:
84c89C11w71h110B96d61H92d10B3p40c97G117X13....
When you are printing the results, change the print statements to
System.out.print(array[i]);
System.out.print(" " + list[i]);
System.out.println();
Output now looks like:
84 c
89 C
11 w
71 h
....
Instead of using int length = fileLength(fileName); to find the length, use int length = fileName.length();
From the format of your file and your current code, it looks like length represents the number of "words" in the file. In your loop, you need to advance i by 2 instead of 1, since it consumes two "words" per iteration. This also means that each array is twice as long as it should be. Instantiate them with length/2.
for (int i = 0; i < array.length; i += 2) {
array[i] = fileScan.nextInt();
list[i] = fileScan.next();
}
Alternately, you could make length represent the number of lines in the file. To do that, use hasNextLine() and nextLine() in your counting loop. Then leave all of the rest of your code as-is.
while (fileScan.hasNextLine()) {
fileScan.nextLine();
counter++;
}
Additionally, make sure your Scanner is passed the proper parameters. A String is valid, but not for File I/O. You would need to first create a File object using the fileName.
Scanner fileScan = new Scanner(new File(fileName));
I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}
I can't understand why my program not functioning. It compiles but nothing is printed. I have a 5 character word in file. I need to read line from that file and then split it into char array, which I then want print out.Thanks!
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
public class test {
public static void main(String[] args)
{
BufferedReader line = null;
char[] array = new char[7];
try{
line = new BufferedReader(new FileReader(args[0]));
String currentLine;
while((currentLine = line.readLine()) != null)
{
array = currentLine.toCharArray();
}
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}//try
catch(IOException exception)
{
System.err.println(exception);
}//catch
finally
{
try
{
if(line != null)
line.close();
}//try
catch(IOException exception)
{
System.err.println("error!" + exception);
}//catch
}//finally
} // main
} // test
Your while loop skips every line except the last one so it could be possible that your last line is empty. To display every line you could have:
while ((currentLine = line.readLine()) != null) {
array = currentLine.toCharArray();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println();
}
Or if you just have the 1 line, You could simply use:
String currentLine = line.readLine();
...
Your program prints only last line
You have to Print in loop.
while (....!=null)
{
array = currentLine.toCharArray();
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}
If above was not a problem than check your file permission.
Check your system may be program is not able to read from file due to permission on file.
Does anybody know how to properly read from a file an input that looks like this:
0.12,4.56 2,5 0,0.234
I want to read into 2 arrays in Java like this:
a[0]=0.12
a[1]=2
a[2]=0;
b[0]=4.56
b[1]=5
b[2]=0.234
I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.
This is the code I tried:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IFFTI {
public static int size=0;
public static double[] IFFTInputREAL= new double[100];
public static double[] IFFTInputIMAG= new double[100];
static int real=0;
static int k=0;
public static void printarrays(){
for(int k=0;k<size;k++){
System.out.print(IFFTInputREAL[k]);
System.out.print(",");
System.out.print(IFFTInputIMAG[k]);
System.out.print("\n");
}
}
public static void readIFFT(String fileName){
try {
Scanner IFFTI = new Scanner(new File(fileName));
while (IFFTI.hasNextDouble()) {
if(real%2==0){
IFFTInputREAL[k] = IFFTI.nextDouble();
real++;
}
else{
IFFTInputIMAG[k] = IFFTI.nextDouble();
real++;
k++;}
}
try{
size=k;
}catch(NegativeArraySizeException e){}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
}
I think this will do what you want:
String source = "0.12,4.56 2,5 0,0.234";
List<Double> a = new ArrayList<Double>();
List<Double> b = new ArrayList<Double>();
Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
while ( parser.hasNext() ) {
List use = a.size() <= b.size() ? a : b;
use.add( parser.nextDouble() );
}
System.out.println("A: "+ a);
System.out.println("B: "+ b);
That outputs this for me:
A: [0.12, 2.0, 0.0]
B: [4.56, 5.0, 0.234]
You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].
You will have to read the complete line.
String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read
Then.. you split the line on the commas or the spaces
String[] values = line.split(" |,");
This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]
Now, just reorganize the contents between the two order arrays.
Reading from a file in Java is easy:
http://www.exampledepot.com/taxonomy/term/164
Figuring out what to do with the values once you have them in memory is something that you need to figure out.
You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:
public class SplitTest {
public static void main(String[] args) {
String raw = "0.12,4.56 2,5 0,0.234";
String [] tokens = raw.split(",|\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
}
EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.
Read the content from the file
Split the string on spaces. Create for each element of the splitted array an array.
String input = "0.12,4.56 2,5 0,0.234";
String parts[] = input.split(" ");
double[][] data = new double[parts.length][];
Split each string on commas.
Parse to a double.
for (int i = 0; i < parts.length; ++i)
{
String part = parts[i];
String doubles[] = part.split(",");
data[i] = new double[doubles.length];
for (int j = 0; j < doubles.length; ++j)
{
data[i][j] = Double.parseDouble(doubles[j]);
}
}
File file = new File("numbers.txt");
BufferedReader reader = null;
double[] a = new double[3];
double[] b = new double[3];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
if ((text = reader.readLine()) != null) {
String [] nos = text.split("[ ,]");
for(int i=0;i<nos.length/2;i++){
a[i]=Double.valueOf(nos[2*i]).doubleValue();
b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
}
}
for(int i=0;i<3;i++){
System.out.println(a[i]);
System.out.println(b[i]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}