I have a text file that looks roughly like this:
type, distance, length, other,
A, 62, 17, abc,
A, 12, 4,,
A, 6, 90,,
A, 46, 53,,
etc.
Everything is separated by commas, but sometimes there is a blank. I need to be able to read this data into an array using a scanner (not bufferedreader) and be able to account for the blanks somehow, as well as split by commas. Later I will need to be able to calculate things with the data in each column. How do I get this data into the array?
This is what I have so far: (java)
import java.util.Scanner;
import java.io.*;
public class RunnerAnalysis {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("File: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.nextLine();
String line = inputFile.nextLine();
while(inputFile.hasNext())
{
String[] array = line.split(",");
}
}
}
If you really want to use a Scanner, which is IMHO not such a good idea, you can set the delimiter to ,.
Scanner inputFile = new Scanner(...);
inputFile.useDelimiter(",");
while (inputFile.hasNext())
{
String type = inputFile.next();
int distance = inputFile.nextInt();
int length = inputFile.nextInt();
String other = inputFile.next();
// Process...
}
I prefer using a BufferedReader in combination with String.split(",").
Related
public static void main(String[] args) throws Exception {
File inputFile = new File("input.txt");
Scanner read = new Scanner(inputFile);
File outputFile = new File("output.txt");
PrintWriter print = new PrintWriter(outputFile);
if (!inputFile.exists()) {
System.out.println("File does not exist!");
}
ArrayList<Event> myArray = new ArrayList<>();
String commands="";
while (read.hasNext()) {
if(commands.matches("AddMovie")){
addMovie(read);
}
}
print.flush();
print.close();
read.close();
}
//java netbeans
public static Event addMovie(Scanner in){
String m[]=new String[6];
for (int i = 0; i < m.length; i++) {
String name=in.next();
Date sDate=new Date(in.next());
Date eDate=new Date(in.next());
double price=in.nextDouble();
String city=in.next();
String address=in.next();
String language=in.next();
String tAudience=in.next();
double raiting=in.nextDouble();
int tickets=in.nextInt();
}
return movie;}
well I am having a problem here so my program must read from a file these given data
AddMovie--The Upside, 6/3/2019, 6/6/2019, 50, Riyadh, Al Qasr Mall, English, Family, 4.5, 40, Comedy, Nicole Kidman, F, 1967
I have to store them in an ArrayList of object and I have to use non-word characters as a delimiter to split these data should I make a method and inside this method a 1-dimensional array and then use split() method?
From what I can understand you are on the right track. Given you read the data you have provided as one single string, you can use the split(",") method on it and store the result of that into an array of strings.
I think that splitting on 'non-word characters' would not be a good idea, as for example you would not want 4.5 to be split into 4 and 5.
I would probably split on ','.
If you were worried about efficiency, it would be a good idea to create a java.util.regex.Pattern object with (for e.g.)
Pattern pat = Pattern.compile(",");
then whenever you wanted to use it, using:
pat.split(theString);
I'm trying to use a constructor to create an object from a file, the file should contain (on the first line) an Int in String format which is meant to be the number of rows for the MD Array and then has a space followed by another Int in String format. I'm trying to "grab" these two Strings, parse them into an int and then instantiate the MD Array by using these two ints I've "grabbed." I'm just not quite sure where I'm going wrong, as I've just begun using File I/O in my coding. Here's my code.
public SeatingChart(File file) throws FileNotFoundException, DataFormatException, IOException
{
Scanner scan = new Scanner(file);
int rows = 0;
int columns = 0;
String rowStr = "";
String colStr = "";
if (scan.hasNext())
{
rowStr = scan.next();
colStr = scan.next();
}
rows = Integer.parseInt(rowStr);
columns = Integer.parseInt(colStr);
seats = new Student[rows][columns];
scan.close();
}
Any help would be much appreciated :)
From your question, You want to grab two numbers, in string format, separated by a space.
I would grab the entire line then trim the string which ensures there is no space before or after the numbers I need. Then split them based on space.
Look at this simplified step by step example. This example will create a file called numbers.txt then put in it string "5 2". Then the file will be read and taken apart to get the numbers.
import java.util.*;
import java.io.*;
import java.nio.*;
PrintWriter fileWriter = new PrintWriter("numbers.txt", "UTF-8");
fileWriter.println("5 2");
fileWriter.close();
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
String numbersString;
if (input.hasNextLine()) numbersString = input.nextLine();
// Trim the string to ensure you have what you need.
numbersString = numbersString.trim();
// Split both numbers according to the space within them.
String[] numsArray = numbersString.split("\\s+");
// Get your numbers.
int row = Integer.valueOf(numsArray[0]);
int col = Integer.valueOf(numsArray[1]);
I want to give a sentence from standard input and my sentence might have a space between it. I want to split the string. How to take input from standard input device?
I can do it with hard coded string.
String speech = "Four score and seven years ago";
String[] result = speech.split(" ");
You can take input from user with nextLine() method of Scanner class
import java.util.Scanner;
public class SplitString
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in/*Taking input from standard input*/);
System.out.print("Enter any string=");
String userInput = scan.nextLine();//Taking input from user
String splittedString[] = userInput.split(" ");//Splitting string with space
}
}
Store the input in a StringBuilder, line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String line;
line = reader.readLine();
Then you can split your result.
String[] result = line.split("\\s");
I want to separate the elements of a text file into different arrays based of whether or not the line contains a question mark. Here is as far as I got.
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
ArrayList<String> Questions = new ArrayList();
ArrayList<String> Other = new ArrayList();
while (fScan.hasNextLine())
{
if(fScan.nextLine.indexOf("?"))
{
Questions.add(fScan.nextLine());
}
Other.add(fScan.nextLine());
}
Quite a few issues there
nextLine() actually returns the next line and moves on the scanner, so you'll need to read once instead
indexOf returns an int, not a boolean, I'm guessing you're more use to C++? You can use any of the following instead:
indexOf("?") >=0
contains("?")
matches("\?") etc.
please follow the java ways and use camelCase for vars...
Code
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("foo.txt"));
List<String> questions = new ArrayList<String>();
List<String> other = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("?")) {
questions.add(line);
} else {
other.add(line);
}
}
System.out.println(questions);
System.out.println(other);
}
foo.txt
line without question mark
line with question mark?
another line
I was trying to take the input of the filename from the user and then proceed to doing all the calculations. but it keeps returning me an error. the file exists in the same directory.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];
for (int i=0; i<rows;i++){
for (int j=0; j<cols;j++) {
matrix[i][j]= scanner.nextDouble();
}
}
System.out.println(rows);
System.out.println(cols);
for (int i=0; i<rows; i++)
{ for (int j=0;j<cols;j++) {
System.out.println(matrix[i][j]);
}
}
}
}
There is one issue with the code. The scanner will just give you the name of the file as string from command line. So, you need to first get the command line argument and then create one more scanner using the constructor which takes file object. e.g.
Scanner scanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
String rowLine = fileScanner.nextLine();
System.out.println(rowLine);
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim())
You realize that you are only using a Scanner of type System.in, right? This means that you aren't even looking at a file, you are looking at user input only. This is regardless of whether you have the first line commented out or not. To use a file, you could use a FileInputStream or a couple other File handling classes.
FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream
Heres the java docs for FileInputStream: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
Edit: After seeing your comment on what the actual error was, I realize there are more problems with the code than just the way you are handling input. Your error is almost certainly happening at one of the first 2 array accessors, the arr1.trim() calls. That means the user input has nothing on the right side of the "=" sign, or there is no "=" sign in the user input.