Read data from file and convert to key value pair - java

I have the below integers in File :
758 29
206 58
122 89
I have to read these integers in an integer array and then need to store the values in key value pair. Then print the output as :
Position 29 has been initialized to value 758.
Position 89 has been initialized to value 122.
I have tried as of now :
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename);
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
String[] line = intStringSplit.split("\t",-1);
data = new int[line.length];
for (int i = 0; i < data.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println(data);
}
linReader.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
return linReader;
}
I am not able to figure out how to get the key and value from the read data.

When posting information related to your question it is very important that you provide the data (in file for example) exactly as it is intended in reality so that we can make a more positive determination as to why you are experiencing difficulty with your code.
What you show as an in file data example indicates that each file line (which contains actual data) consists of two specific integer values. The first value being the initialization value and the second being the position value.
There also appears to be a blank line after ever line which contains actual data. This really doesn't matter since the code provided below has a code line to take care of such a thing but it could be the reason as to why you may be having difficulty.
To me, it looks like the delimiter used to separate the two integer values in each file line is indeed a whitespace as #csm_dev has already mentioned within his/her comment but you claim you tried this in your String.split() method and determined it is not a whitespace. If this is truly the case then it will be up to you to determine exactly what that delimiter might be. We couldn't possibly tell you since we don't have access to the real file.
You declare a File object within your provided code but yet nowhere do you utilize it. You may as well delete it since all it's doing is sucking up oxygen as far as I'm concerned.
When using try/catch it's always good practice to catch the proper exceptions which in this case is: IOException. It doesn't hurt to also display the stack trace as well upon an exception since it can solve a lot of your coding problems should an exception occur.
This code should work:
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename); // why do you have this. It's doing nothing.
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
// If the file line is blank then just
// continue to the next file line.
if (intStringSplit.trim().equals("")) { continue; }
// Assuming at least one whitespace is used as
// the data delimiter but what the heck, we'll
// use a regular expression within the split()
// method to handle any number of spaces between
// the integer values.
String[] line = intStringSplit.split("\\s+");
data = new int[line.length];
for (int i = 0; i < line.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println("Position " + data[1] +
" has been initialized to value " +
data[0] + ".");
// do whatever else you need to do with the
// data array before reading in the next file
// line......................................
}
linReader.close();
}
catch (IOException ex) {
System.out.println("File Not Found");
ex.printStackTrace();
}
return linReader;
}

Related

reading comma separated text files of different lengths in java

so I have a text file and i am trying to read line by line and then populate my array list.
a sample text file is shown below:
10,11,11/10/2021,24,1,2
11,12,11/10/2021,1,2,3
12,13,11/10/2021,24,5
13,14,11/10/2021,1,11,32,2
14,15,11/10/2021,1,9,8
I have been able to read in the first 4 elements (ID,ID,date,price)
and then i need to populate the other elements on that line into an array list (all elements after price)
the problem I am having is that it populates all the other lines into the array list and just not the remaining elements for the one line.
here is the code
int ID = 0;
int spareID = 0;
String date = "";
float fee = 0;
ArrayList<String> limits = new ArrayList<String>();
ArrayList<Import> imports= new ArrayList<Imports>();
File myfile = new File("file.txt");
try {
Scanner inputFile = new Scanner(myfile);
inputFile.useDelimiter(",");
// setting comma as delimiter pattern
while (inputFile.hasNextLine()) {
ID = inputFile.nextInt();
SpareID = inputFile.nextInt();
date = inputFile.next();
fee = inputFile.nextFloat();
while (inputFile.hasNext()) {
limits.add(inputFile.next());
}
Import import = new Import(ID, spareID, fee, date, limits);
imports.add(import);
}
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("error: can not find file");
}
the array list is capturing the rest of the text file when i need it to capture just the remaining elements on that line.
Edit: the first 4 elements of the line will all go into a different variable and then I need the rest or the elements on that line only to go into the array list
Use Scanner.nextLine() to get a single line, then create a second Scanner with that line to parse it contents.
Scanner inputFile = new Scanner(myfile);
while (inputFile.hasNextLine()) {
Scanner line = new Scanner(inputFile.nextLine());
// setting comma as delimiter pattern
line.useDelimiter(",");
ID = line.nextInt();
SpareID = line.nextInt();
date = line.next();
fee = line.nextFloat();
while (line.hasNext()) {
limits.add(line.next());
}
}
inputFile.close();

This code is supposed to get N values from the user. Then input then into a .txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");

Can't compare the first line of .txt file with a string

I want to send studentGrade array to "calculate" method to calculate the average of grades but if the first line of text file is parameter, I can't. When the "if" method running, it goes back to while loop, even though two strings are equal.
I've tried to change the first line of .txt, in case of there is a problem. But the result was the same. It never does compare if the wanted person is in the first line.
static int studentNumber = 0;
static String[] studentGrade;
static String studentName = "";
static void makeList(String name) {
try(Scanner sc = new Scanner(new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\new_1.txt")))) {
boolean flag = true;
while (sc.hasNextLine()) {
flag = true;
String studentLine = sc.nextLine();
studentGrade = studentLine.split(",");
studentName = studentGrade[0];
if (studentName.equalsIgnoreCase(name)){
calculate(studentGrade);
flag = false;
break;
}
}
if (flag)
System.out.println("Couldn't found!");
}
catch (FileNotFoundException e) {
System.out.println("An error occured when the file was tried to opened.");
}
}
static void calculate(String[] a) {
int note1 = Integer.parseInt(a[1]);
int note2 = Integer.parseInt(a[2]);
int note3 = Integer.parseInt(a[3]);
double avg = Math.ceil((double)(note1 + note2 + note3) / 3);
System.out.println(a[0] + "'s average is: " + (int)avg);
}
I expect the if case would be true and sent the array to "calculate" method. It does its job except the student is in the first line of .txt file. For example if user input is Michael, it says "Couldn't found!" but if the input is John, it gives its average.
//First lines of .txt file
Michael,70,90,20
John,90,80,60
Molly,60,30,50
I created a file with the values you are giving:
Michael,70,90,20
John,90,80,60
Molly,60,30,50
And when I try your code, it seems to work fine:
makeList("Michael");
makeList("John");
makeList("Molly");
return
60
77
47
My suspicion is that you have some kind of invisible character at the very beginning of your file, and that is what makes your equality fail. I encountered this kind of issue several time when parsing XML and the parser would complain that my file doesn't start with an XML tag.
Can you try to make a brand new file with these 3 lines and try your program again on this new file?
Here is a much simpler and clearer way to do this:
try (Stream<String> lines = Files.lines("C:\\Users\\User\\Desktop\\new_1.txt")) {
Optional<String[]> studentGradesOpt =
lines.map(line -> line.split(","))
.filter(row -> row[0].equalsIgnoreCase(name))
.findFirst();
studentGradesOpt.ifPresent(grades -> calculate(grades));
if (!studentGradesOpt.isPresent()) {
System.out.println("Couldn't find student " + name);
}
}

Reading information from a textfile to get specific information

I am working on an assignment where I have to create an interval(which I have already completed) and from a text file, read in the girls names that are found within the interval and put them into an array list. I also have to read in all the male names that start with the letter "J", and then calculate how many male births start with the letter "J" and print out that information. Below is the code I have so far:
public static int generateRandomInt(int lowerLimit, int upperLimit) {
int value = lowerLimit + (int)Math.ceil( Math.random() * ((upperLimit - lowerLimit) + 1)); //generates a random number between 1 and 10
return value;
}// end generateRandomInt
public static void main(String[] args) {
// Read from filename: top20namesNM1994.txt
// Generating a interval, the lower random number comes from 50 to 100, and the upper random number comes from 150 to 200.
// Print out this interval
// Read all the girls names, which birth numbers are inside of the interval you construct, into a array or ArrayList.
// Print out the array.
//Print out all the males names, which start with letter "J".
//Determine how many male births start with names starting with the letter "J", and print out the summary information.
final int LOW1 = 50;
final int LOW2 = 100;
final int HIGH1 = 150;
final int HIGH2 = 200;
ArrayList<String>girlNames = new ArrayList<String>();
String line = "";
int interval_low = generateRandomInt(LOW1, LOW2);
int interval_high = generateRandomInt(HIGH1, HIGH2);
System.out.println("The interval is ( " + interval_low + " , " + interval_high + " )" );
try {
FileReader inputFile = new FileReader("C:\\Users\\drago\\eclipse-workspace-Ch6to7FinalExam2\\MorrisJFinalExam2\\src\\top20namesNM1994.txt");
//Scanner scan = new Scanner (inputFile);
BufferedReader br = new BufferedReader(inputFile);
while((line = br.readLine()) != null) {
line.split("\\s+");
if()
girlNames.add();
}
}
catch(IOException e) {
System.out.println("File not Found!");
}
if()
System.out.println(girlNames.toString());
}
I am stuck on how to get the girl names that are within the interval created and also how to read in the boy names. Attached is the text file.
TextFile
Okay...you know how to read in the text file (somewhat) which is good however you can simplify the code a bit:
ArrayList<String> girlNames = new ArrayList<>();
String filePath = "C:\\Users\\drago\\eclipse-workspace-Ch6to7FinalExam2\\"
+ "MorrisJFinalExam2\\src\\top20namesNM1994.txt";
String line = "";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
while ((line = br.readLine()) != null) {
// .....................
// ..... Your Code .....
// .....................
}
}
catch (IOException ex) {
ex.printStackTrace();
}
Try With Resources is used here so that your BufferedReader is automatically closed. If all your going to do is read the desired text file then the Scanner object you have commented out in your code is also a pretty good alternative for reading text files if properly used.
It's obvious from your incomplete code that each data line within this file is White-Space or Tab delimited simply based on the Regular Expression ("\\s+") used within the String#split() method (the "\\s+" expression will split a string on any number of white-spaces and or tabs that are contained within that string). Do Note however that the code line where you are using the String#split() method is not completed properly.... If you read the linked tutorial you will find that this method is used to fill a String Array which is good because usually, this is what you want to do with file data lines. Doing so of course allows you to retrieve the exact data portion desired from each data file line.
No one here has a clue what is contained within your specific data text file because like so many others the contents within it is obviously so supper-duper classified that not even fictitious data will suffice. Because of this there is in no way a means provide you with an accurate array index value or values to use against your String Array in order to retrieve your desired data from each data file line. This is good however since it is you who needs to figure this out and once you do you will have the task beaten to submission.

Java - reading .txt file to arrayList omits last iteration and shows error

I have a .txt file and require its contents to be put into an arraylist.
It is in the following format, Each element(int,String) being on a new line within the document.
int number of parts
string partname
string description
int price
string partname
string description
int price
etc.
Whenever i run my program it will add the first however many attributes, but will not add the last three attributes to the arraylist.
public static void loadPartsCleanly(){
try {
// java.io.File file = new java.io.File("parts.txt");
Scanner in = new Scanner(new File("parts.txt"));
ArrayList<Part> partlist = new ArrayList<Part>();
String name=null;
String description = null;
double price =0.0;
int totalParts = 0;
totalParts = in.nextInt();
in.nextLine();
//totalParts ++ ;
System.out.println(totalParts);
for (int i = 0; i < totalParts; i++)
{
//ArrayList<Part> partlist = new ArrayList<Part>();
name = in.nextLine();
description = in.nextLine();
price = in.nextDouble();
in.nextLine();
int quantityInStock = 5;
partlist.add(new Part(name, description, price, quantityInStock));
System.out.println(partlist);
}
in.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Unable to locate the parts.txt file for opening.");
} catch (Exception otherExc) {
System.out.println("***** An unexpected error has occurred *****");
otherExc.printStackTrace();
}
}
so in the above code it reads the first Int in the text document and assigns it for use in the for loop.
totalParts = in.nextInt();
in.nextLine();
//totalParts ++ ;
System.out.println(totalParts);
for (int i = 0; i < totalParts; i++)
The loop works fine up until the last part needs to be added to the arraylist, regardless of whether totalParts is 8 or 20.
Which gives this error..
An unexpected error has occurred java.util.NoSuchElementException: No
line found
I have been trying to figure this out but increasing frustration has prompted me to post on here, so any pointers in the right direction would be greatly appreciated. If you need clarification with anything regarding my question, please ask.
The nextInt() and nextDouble() methods are different than nextLine(). nextLine() reads the \n but the others.
So, if you have each element in a different line, you should use nextLine() always and then parse that line to the type that you want, for example:
String line = in.nextLine();
double price = Double.parseDouble(line);
I think the last line of your input file is a number.
What I saw from your code is that you use nextDouble to read the price and then you use nextLine to go to next line.
In such situation, if there is no more line behind the last number, you got error.
The following code solves your problem.
if (i + 1 < totalParts) {
in.nextLine();
}

Categories