Scanner NextInt() using a comma separated coordinate - java

I am trying to parse information from a text file in the following format:
WarningGeotask: 0, 1
The first word is a keyword for a certain object to create at the coordinate location given in the numbers that follow it. Here is what my loop looks like currently:
// Open file and scan for a line
File f = new File("Simulation.Configuration");
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
// Parse each line with a temporary scanner
String line = s.nextLine();
Scanner s2 = new Scanner(line);
// Get keywords from the file to match to variable names
String keyword = s2.next();
//...Multiple if statements searching for different keywords...
else if (keyword.equals("WarningGeotask:")) {
int xCoord = s2.nextInt();
int yCoord = s2.nextInt();
WarningGeotask warningGeotask = new WarningGeotask(xCoord, yCoord);
s2.close();
continue;
}
}
However, this code doesn't work properly. In fact, String xCoord = s2.nextInt() throws an error. I can do s2.next() and print out s2.nextInt() which returns 1. But I'm not sure what I'm doing wrong with Scanner to get 0 and 1 set to two different variables. Thanks for the help!
EDIT: The String variables xCoord and yCoord are supposed to be int - my fault.

The thing is that Scanner#nextInt() returns a numerical value (to be exact: a value of type int), which you try to assign to a String variable.
So instead of:
String xCoord = s2.nextInt();
String yCoord = s2.nextInt();
try:
int x = s2.nextInt();
int y = s2.nextInt();

You can do this using split()
when you read the lines, make it as Comma-separated value :
while (s.hasNextLine()) {
String line = s.nextLine().replace(":",",");
String[] data =line.split(",");
//...Multiple if statements searching for different keywords
else if(data[0].equals("WarningGeotask:")){
WarningGeotask warningGeotask = new WarningGeotask(Integer.parseInt(data[1].trim()), Integer.parseInt[data[2].trim());
}

try this
sc.useDelimiter("\\D+");
int n1 = sc.nextInt();
int n2 = sc.nextInt();

Related

Making an array out of doubles from a text file

I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:
90.0
71.5
87.9
95.0
98.1
Code:
File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();
//create array
double[] array = new double[12];
//variable to increment
int u = 0;
//loop to put data into array
while(gradesFile.hasNextDouble())
array[u] = gradesFile.nextDouble();
u += 1;
gradesFile.close();
A. As #hnefatl said you need to group statements in the loop,
while(<condition>) {
statement1;
...
statementN;
}
otherwise only next one executes.
while(<condition>) statement1;
...
B. When you did String line = gradesFile.nextLine();
you got full first line from file and Scanner position is at next line if there is any.
So by doing gradesFile.hasNextDouble() after that, Scaner looks for double in next line.
If you'd like to use nextLine() and your doubles are "one-per-line" you need to work with them in a loop as:
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextLine()) {
String line = gradesFile.nextLine();
array[u] = Double.parseDouble(line);
u += 1;
}
gradesFile.close();
or if you'd like to use nextDouble() you do not mix it with nextLine()
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextDouble()) {
array[u] = gradesFile.nextDouble();
u++;
}
gradesFile.close();
You can simply scan the double value in your file and store in the array as below
Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;
try {
scan = new Scanner(file);
//Scan while the file has next double value
while(scan.hasNextDouble())
{
//Save the double value read from text file and store to array
array[i] = scan.nextDouble();
i++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
To print what you have stored in your array
for(int y = 0; y < array.length;y++)
{
System.out.println(array[y]);
}

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]);
}

i need help for my code which uses scanner

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]);
}
}
}

Categories

Resources