i need help for my code which uses scanner - java

i am writing a code that reads input from a file and writes into another after some processing ofcourse.
now, my input file is,
4
0 1
0 2
0
0 3
3
0
0
0
E
and what i need to do is copy elements on left to an array in first column and elements on right to second column.
i used scanner but it does not recognize end of line.
help me!!!!
this is what i tried.
i tried copying lines and then modifying it.
for (i = 0; i < size; i++) {
if (!f1.hasNext(endPage)) {
String temp1 = f1.next();
String temp2 = f1.next();
int a[] = new int[4];
a[0] = (int) temp1.charAt(temp1.length() - 1);
a[1] = (int) temp2.charAt(temp1.length() - 1);
a[2] = (int) temp1.charAt(temp1.length() - 2);
a[3] = (int) temp1.charAt(temp1.length() - 2);
scales[i].weightOnLeft = a[0];
scales[i].weightOnRight = a[1];
scales[i].left = scales[a[2]];
scales[i].right = scales[a[3]];
}
}

Try this way:
Scanner input = new Scanner(new File("..."));
while(input.hasNextLine())
{
String data = input.nextLine();
}

Try to use the Scanner to read line by line and then split(on space, in your case) your line to get the tokens.
Scanner f1 = new Scanner(new File("yourFileName.extn"));
while(input.hasNextLine()) {
String line = f1.nextLine();
String[] tokens = line.split(" "); // Splitting on space
// Do what you want with your tokens
// Since not all lines have equal no. of tokens, you need to handle that accordingly
}

Try like this below:-
In your first column it will store on array[0] and second column value will store on array[1]. Also for second column you need to check the condtion as written below. Please follow:-
File file=new File("/Users/home/Desktop/a.txt");
String[] aa=new String[2];
try {
Scanner sc=new Scanner(file);
while (sc.hasNextLine())
{
String ss=sc.nextLine();
aa=ss.split("\\s");
//it will store left column value in this index
System.out.println("aa[0]"+aa[0]);
if(aa.length>1)
{
//it will store right column value in this index
System.out.println("aa[1]"+aa[1]);
}
}
}

Related

When using in.hasNextInt(), how do I skip a string that follows in the same line?

After extensive searching I've not been able to come across a similar question/solution. Below is what I've written, followed by the input, and unsuccessful output. Due to the fact that it's storing the first value to create array[13], yet my array finishes empty, I suspect the comment in the first line is what's causing trouble. I should mention that I couldn't find a way to implement the .split/.replace methods since I'm working with ints and strings and I feel parsing would be a mess. I'm sure there's a workaround I'm missing here.
So,
TL;DR : Failure to store anything after '13' – How do I skip, or line break at the "//" in the first line in the input file after storing '13'? ( If that's even what's going wrong here. )
Program :
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
String inf = JOptionPane.showInputDialog("Input file path?");
java.io.FileReader inFile = new java.io.FileReader(inf);
Scanner in = new Scanner(inFile);
String outf = "./" + JOptionPane.showInputDialog("Name of new output file?");
PrintWriter outFile = new PrintWriter(outf);
int index = in.nextInt();
int array[] = new int[index];
MyArray MA1 = new MyArray();
int i = 0;
while (in.hasNextInt() && i < 13) {
if (in.next().contains("//")){
in.nextLine();
continue;
}
System.out.println(in);
array[i] = in.nextInt();
i++;
}
System.out.println(Arrays.toString(array));
}}
Input :
https://textuploader.com/15h1x
Output :
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Expected :
[573, 2739, 76321, 3873, 73430, 333, 7293, 38383, 272, 946, 3832, 8410, 2583]
Thanks for any help
Just use nextLine() everytime and then do the stuff you need :
while (in.hasNextLine() && i < 13) {
line = in.nextLine();
intval = line.split("\\s+")[0]; // check for lines with comment
array[i] = Integer.parseInt(intval);
i++;
}
To read the ints that are after the 14th value :
List<Integer> remainingInts = new ArrayList<>();
while (in.hasNextLine()) {
line = in.nextLine();
intval = line.split("\\s+")[0]; // check for lines with comment
remainingInts.add(Integer.parseInt(intVal));
}
Your code didn't work because your while loop was never getting executed since each line of the file was being loaded as a String not an int. This also explains why your array contained only zeros.
Change your while-loop to the following :
int array[] = new int[13];
int i = 0;
in.nextLine(); // skip the first line
while (in.hasNextLine() && i < 13) {
String currLine = in.nextLine();
array[i] = Integer.parseInt(currLine.split("\\s+")[0]);
i++;
}
System.out.println(Arrays.toString(array));
This outputs :
[573, 2739, 76321, 3873, 73430, 333, 7293, 38383, 272, 946, 3832,
8410, 2583]
If you're on java-8 and higher, the entire operation can be done in a single line
int[] array = Files.lines(Paths.get(inFile))
.mapToInt(line -> Integer.parseInt(line.split("\\s+")[0]))
.skip(1) // skip first element
.limit(13) // upto 13 only
.toArray(); // convert to array

java replacing elements of an array

The main question will be at the bottom. From the text file below, lets say the first integer is a, second is b, and third is c and so forth. the program takes a,b and c, parses them, puts them into myCalculations method which returns a string with two integers. The string is parsed, a and b are replaced the integers in said returned string, then the next iteration of the loop will take the new values for a and b, and integer d. This will continue until the end where a and b are printed to the user.
The input from a two text files is as follows:
The format of the text file is as follows:
200 345
36
45
36
21
Here is the reading in from the file, it works as intended, I put it here for context. tl;dr is results[] is an integer array for the first line. (int a and b)
public class conflictTrial
{
BufferedReader in;
public static void conflictTrial() throws FileNotFoundException
{
System.out.print('\u000c');
System.out.println("please enter the name of the text file you wish you import. Choose either costs.txt or lotsacosts.txt Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
BufferedReader in = new BufferedReader(new FileReader(file));
String element1 = null;
try {
element1 = in.readLine();
}catch (Exception e) {
// handle exception
}
String[] firstLine = element1.split(" ");
Arrays.stream(firstLine).forEach(fl -> {
//System.out.println("First line element: \t\t\t" + fl);
});
int[] results = new int[100];
for (int i = 0; i < firstLine.length; i++)
{
try {
int stuff = Integer.parseInt(firstLine[i]);
results[i] = stuff;
}
catch (NumberFormatException nfe) {
// handle error
}
}
The bufferreader reads in the file, the for loop parses the integers into array results[]. Next, the remaining lines are parsed and method myCalculations is called:
String otherElement = null;
int[] aliveSoldiers = new int[100];
int [] things = new int [100];
int[] newResults = new int[100];
try {
while ((otherElement = in.readLine()) != null) { // main loop
System.out.println("Line to process:\t\t\t" + otherElement);
String[] arr = otherElement.split(" ");
for (int k = 0; k <arr.length; k++)
{
int thingsResult = Integer.parseInt(arr[k]);
things[k] = thingsResult;
System.out.println("number of days: \t\t\t"+things[k]);
aliveSoldiers[0] = results[0];
aliveSoldiers[1] = results[1];
String returnAliveSoliders = myCalculations(aliveSoldiers[0], aliveSoldiers[1], things[k]);
System.out.println("return soldiers alive: \t\t"+returnAliveSoliders);
String[] newItems = returnAliveSoliders.split(" ");
for (int f = 0; f < newItems.length; f++)
{
int newParse = Integer.parseInt(newItems[f]);
newResults[f] = newParse;
aliveSoldiers[0] = newResults[0];
aliveSoldiers[1] = newResults[1];
}
k++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently the code does the following: first of the main loop iteration takes integer a, b and c, second iteration takes the same integers a and b (200 and 345, the initial values) with integer d, the third iteration takes the same values for and a and b with integer e. I have attempted to address this issue with the following code:
aliveSoldiers[0] = newResults[0];
aliveSoldiers[1] = newResults[1];
I need to take the integers from the method myCalculations (parsed in the k-modifier loop), and overwrite them into aliveSoldiers[0] and aliveSoldiers [1] so the program reads the next line, takes the new integers, and continues until there are no more days remaining.
I honestly haven't understood what the whole exercise should do, but the code You enlighted could be wrong due to the indexes You use: those indexes are always 0 and 1, even if cycles are performed through some other indexes. At the end of the second code snippet, the f-for modify the array "newResults" at the increasing index "f", but that array is read always at the same index: 0 and then 1. So, if "f" gets higher values than "1" then the "aliveSoldiers"'s elements are left unchanged.
In particular, aliveSoldiers is modified only on the first two indexes, the other indexes are not used at all.
Do you need a stack-like or queue-like behaviour?

Reading a file with Strings and floats and assigning them to arrays

I want to design a code that can read a file that looks like this:
Jake 12.00 13.24 6
Sarah 11.23 24.01 8
Alex 10.65 19.45 4
I need to make separate arrays for the Strings, the first float, the second float, and the int.
How do I go about doing this?
This is what I have so far: I'm not sure how to make separate arrays for the two floats. I also keep getting an exception IndexOutOfBoundsException: 0 at EmployeePay.main..
import java.util.Scanner;
import java.io.*;
public class EmployeePay {
public static void main(String[] args) throws FileNotFoundException {
if (args.length != 1) {
final String msg = "Usage: EmployeePay name_of_input file";
System.err.println(msg);
throw new IllegalArgumentException(msg);
}
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner scanner = new Scanner(new BufferedReader(new FileReader(input)));
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%s %-10s %-20s %-30s", Id, Hours, WageRate, Deductions);
int lineNumber = 0;
while (scanner.hasNextLine()){
lineNumber =lineNumber +1;
String [] Identification= new String [lineNumber-1];
int [] TotalDeductions = new int [lineNumber-1];
float [] WorkTime = new float[lineNumber-1];
if(scanner.hasNextInt()){
TotalDeductions[lineNumber-1] = scanner.nextInt();
System.out.println(TotalDeductions[lineNumber-1]);
}
else if (scanner.hasNextFloat()){
WorkTime[lineNumber-1]= scanner.nextFloat();
}
else {
Identification[lineNumber-1] = scanner.next();
System.out.println(Identification[lineNumber-1]);
}
}
}
}
I will assume your String value doesn't contain space. This is kind of pseudo code, Try yourself and explore each line why I did so:
String s[] = new String[size];
float f1[] = new float[size];
float f2[] = new float[size];
for(int i=0; i<numberOfLines;i++) {
String x = "Jake 12.00 13.24 6";
String[] arr = x.split(" ");
s[i] = arr[0];
f1[i] = Float.valueOf(arr[1]);
f2[i] = Float.valueOf(arr[2]);
}
This error exception IndexOutOfBoundsException: 0 at EmployeePay.main. is occuring due to this statement if (args.length != 1).
It should be if(args.length!=0)
If no arguements are passed at command prompt then args.length is 0. So, this statement will throw an exception final String inputFileName = args[0];
Thus, you need to check for args.length
If your data file is indeed as you show in your post with blank lines between the data lines then you will need to take care of those as well while reading the file and processing the information obtained. You obviously want to skip past those particular lines. If this isn't the case then it only goes to show you how important it is to provide full and accurate information when asking a question here. No one here wants to really assume anything.
When creating arrays it's always nice to know how big an array needs to be beforehand so that you can properly initialize it to its required size. This is where List or ArrayList is better, you can just add to them when needed. Never the less, to properly initialize all your different arrays (String[], float[], float[], and int[]) you need to know how many valid data line are contained within your data file. By valid data lines I mean lines that actually contain data, not blank lines. So the first natural step would be to count those lines. Once you have the count then you can initialize all your arrays to that line count.
Now all you need to do is re-read the file data line by line, split each line to acquire the data segments , then convert each numerical segment to its respective Array data type. Once you have all your arrays filled from the file you can then do whatever you like with the data contained within those arrays. The code to carry out this task might look something like this:
String inputFileName = "MyDataFile.txt";
Scanner scanner;
int linesCount = 0;
try {
// Count the total number of valid data lines
// within the file (blank line are skipped).
scanner = new Scanner(new File(inputFileName));
while (scanner.hasNextLine()) {
String strg = scanner.nextLine().trim();
if (!strg.equals("")) { linesCount++; }
}
// Declare our different Arrays and size them to
// the valid number of data lines in file.
String[] employeeID = new String[linesCount];
float[] hours = new float[linesCount];
float[] wageRate = new float[linesCount];
int[] deductions = new int[linesCount];
// Read through the file again and place the data
// into their respective arrays.
scanner = new Scanner(new File(inputFileName));
int counter = 0;
while (scanner.hasNextLine()){
// Get the next line in file...
String strg = scanner.nextLine().trim();
// If the file line is blank then skip it.
if (strg.equals("")) { continue; }
// otherwise split the line by its space
// delimiter ("\\s+" takes care of 1 OR more
// spaces just in case).
String[] values = strg.split("\\s+");
// Add to the employeeID string array.
employeeID[counter] = values[0];
// Control what is placed into the elements of each
// float or integer array. If there is no value data
// supplied in file for the employee Name then make
// sure 0.0 (for floats) or 0 (for integers) is placed
// there after all, you can't parse a null string ("").
if (values.length >= 2) { hours[counter] = Float.parseFloat(values[1]); }
else { hours[counter] = 0.0f; }
if (values.length >= 3) { wageRate[counter] = Float.parseFloat(values[2]); }
else { wageRate[counter] = 0.0f; }
if (values.length == 4) { deductions[counter] = Integer.parseInt(values[3]); }
else { deductions[counter] = 0; }
counter++;
}
scanner.close();
// Now that you have all your arrays you can
// do whatever you like with the data contained
// within them:
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%-15s %-15s %-15s %-15s%n", Id, Hours, WageRate, Deductions);
for (int i = 0; i < employeeID.length; i++) {
System.out.printf("%-15s %-15s %-15s %-15s%n", employeeID[i], hours[i], wageRate[i], deductions[i]);
}
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }

How to scan for integers in a line that has already been scanned with scan.nextLine()

I'm trying to write a method that scans a text file and adds all lines that start with # to a String called metadata. After that I want to scan the next three integers, starting in the first line that does not contain a #. However, the first line that does not contain a # gets skipped because I already used scan.nextLine() to scan it.
File file = new File(filename);
Scanner scan = new Scanner(file);
String format = scan.nextLine();
String metadata = "";
//This loop adds all lines starting with # to metadata.
outerloop:
while(scan.hasNextLine()){
String line = scan.nextLine();
if(line.startsWith("#")){
metadata = metadata+line;
} else {
break outerloop;
}
}
//Scans the next three integers and sets them equal to width, height, and maxRange.
int width = scan.nextInt();
int height = scan.nextInt();
int maxRange = scan.nextInt();
My input is a text file. The first six lines are shown in this screenshot.
There is only one line starting with #, however my method has to be able to handle a file with multiple lines starting with #. The output should be
format = "P3"
metadata = "# CREATOR: GIMP PNM Filter Version 1.1"
width = 200
height = 133
maxRange = 255
However instead I get
format = "P3"
metadata = "# CREATOR: GIMP PNM Filter Version 1.1"
width = 255
height = 183
maxRange = 187
Your line is a String. You can search for all substrings matching the following regex:
[0-9]+
This can be done in a following way:
List<String> matches = new ArrayList<>();
Matcher m = Pattern.compile("[0-9]+")
.matcher(readLineWhichIsString);
while (m.find()) {
matches.add(m.group());
}
int[] numbersInLine = new int[matches.size()];
for (int i = 0; i < matches.size(); i++) {
numbersInLine[i] = Integer.parseInt(matches.get(i));
}
The above solution will match 12 from 12a. If you don't want it, just change the regex. I'll make some research for you.
Matcher m = Pattern.compile("[0-9]+(?=\\s|$)")
will only match those Strings that are digits followed by a space or end of String.
Edit:
The below code will fill int[] values with your int parameters.
String line;
while(scan.hasNextLine()){
line = scan.nextLine();
if(line.startsWith("#")){
metadata = metadata+line;
}else{
break outerloop;
}
}
int[] values = new int[3];
List<String> matches = new ArrayList<>();
Matcher m = Pattern.compile("[0-9]+(?=\\s|$)")
.matcher(readLineWhichIsString);
while (m.find()) {
matches.add(m.group());
}
int i = 0;
for (i = 0; i < Math.min(matches.size(), values.length); i++) {
numbersInLine[i] = Integer.parseInt(matches.get(i));
}
while (i < 3) {
values[i] = scan.nextInt();
}
Your problem is in logic when you check for # in line and it is not you want to read that line again
here is a proposed solution
//This loop adds all lines starting with # to metadata.
String line = null;
while(scanner.hasNextLine()){
line = scanner.nextLine();
if(line.startsWith("#")){
metadata = metadata+line;
}else{
break ;
}
}
//Scans the next three integers and sets them equal to width, height, and maxRange.
String ints[]=line.split(" ");
int width = Integer.parseInt(ints[0]);
int height = Integer.parseInt(ints[1]);
int maxRange = scanner.nextInt();
This works and you get desired reuslt
and why to re read a file when you have the line already

How to read file line by line to an array in Java skipping first int?

I am trying to read a file in Java and store it into an array. Now the problem is that the file has the following structure. I will give 2 example files below:
input file structure
<number of lines>
<line number> <value>
.
.
.
<line number> <value>
input1.txt
5
1 34
2 19
3 43
4 62
5 36
input2.txt
4
1 10.3430423
2 -34.234923
3 -100.39292
4 22
As you can see the file starts with the number of lines(e.g 4 or 5). In the normal input text I have there are more than 100000 lines.
So my code basically grabs the user input, opens the file, create an array size and an array of that size. Now I am stuck on reading the next line and adding the values to my elements array. The line number should not be added into the array. Now as you can see, my elements array is declared as String. Is it possible to actually read the file, get the type of the value and create an array of that type? I think it could save from converting from string to int or double or floating?
Below is my code:
public static void main(String args[]) throws NumberFormatException, IOException{
String inFile; //Input file name.
int filterSize; //Filter size (odd integer >= 3).
String outFile; //Output file name.
int arraySize;
String[] elements;
int index = 0;
//Scanner to take input file name, filter size and output file name.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter your keyboard input as follows: <data file name> <filter size(odd int >= 3> <output file name>");
//Assigning values to variables.
inFile = keyboardInput.next();
filterSize = keyboardInput.nextInt();
outFile = keyboardInput.next();
//Reading file into array using BufferReader
BufferedReader fileInput = new BufferedReader(new FileReader(inFile));
arraySize = Integer.parseInt(fileInput.readLine()); //Get Array Size
elements = new String[arraySize];
while(fileInput.readLine() != null){
elements[index] = fileInput.readLine();
index += 1;
}
}
Any help is appreciated. Thanks.
Try doing it like this:
Scanner sc = new Scanner(new File(inFile));
arraySize = sc.nextInt();
elements = new String[arraySize];
while(sc.hasNext())
{
sc.nextInt();
elements[index] = sc.next();
index += 1;
}
You create new Scanner and you can than read integers, booleans and so on, without any converting. Because you don't need line of current number, you just read that number and that is it. You don't need to save it anywhere. Then the next number/string you must save at elements[index]. That's it
Go stream-based:
Files.lines(pathToFile).skip(1) // skip the line counter. Don't trust input
.map(line -> line.replaceFirst("\\d+", "")) // remove digits at the start
.collect(Collectors.toList()); // collect it into a list
You can Store it into an array with .toArray() anyways
But actually you should do that with a try-with-resources:
try (Stream<String> lines = Files.lines(pathToFile).skip(1)) {
elements = lines.map(line -> line.replaceFirst("\\d", "")).collect(Collectors.toList());
} catch (IOException e) {
// sensible handling...
}
Read the number, never use it.
File file = new File("input1.txt");
Scanner in = new Scanner(file);
int lines = in.nextInt();
int []a = new int[lines];
for(int i = 0; i < lines; i++)
{
int fakeNumber = in.nextInt();//read it but never used it
a[i] = in.nextInt();
}
You could also use in#hasNextLine() also.
The real question here is how to get rid line number and get the value besides it.
double[] array = .... // initialize your array
int v = 0;
while(file.readLine() != null){
// your array
array[v++] = Double.parseDouble(file.readLine().split(" ")[1]);
}

Categories

Resources