I want to be able to read a text file for its rows and columns and put the data in a matrix. this is what i got so far. i have a matrix class with one data member called element of type int and it's a 2-d array [][].
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(fin);
scanner.next(); // removes the first line in the input file
int rows = scanner.nextInt();
int cols = scanner.nextInt();
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
System.out.println(rows);
System.out.println("/n");
System.out.println(cols);
}
}
The sample text file is as follows. I want to take the rows and columns so i can dynamically declare the matrix and then store its values. i get the error saying INPUTMISMATCH exception. help would be appreciated.
<matrix>
rows = 2
cols = 2
1 2
2 4
</matrix>
From the javacdocs, an InputMismatchException is thrown "if the next token does not match the Integer regular expression, or is out of range".
You're trying to scan a string "row = 2" as an integer. You can't use nextInt in this case. Try nextLine and then split on = to get the value.
Example:
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
Related
i have a text file and i want to read the integers and doubles. I dont know how many values i have to read. The first value in the line is always the integer and the second is always the double. I want to save the value of the first line seperately.
200
11010 0.004
500 0.02
637 0.018
How to create 2 arrays and save the values, so i can use them later? I am not allowed to create a new class. I tried to use Point but cant store doubles.
Scanner scanner = new Scanner(new File(args[0]));
int cores= scanner.nextInt();
System.out.print(cores);
while (scanner.hasNext()) {
int x = scanner.nextInt();
double y = scanner.nextDouble();
System.out.printf("x");}
I' ve tried the code above but throws out Exception
You can use simple file handling approach to read the file line by line, For the first line you can use a flag to mark the line and sent the file to remote location you want to save the data. Then for all later lines you can split the string on the basis of " " (space). Post which once you have stripped the elements of the resulting array you can typecast and append the element at first index to integer array. And the second element (typecast before append) to the double array. This shall work absolutely fine with any length of file.
A demo code for the same is as following:
public class ReadLineByLine
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis);
String tempLineData = "";
int flag = 0;
String[] elements;
List<Integer> ints = new ArrayList<Integer>(
List<Float> floats = new ArrayList<Float>(
while(sc.hasNextLine())
{
if(flag == 0){
// Place the operation with the first line here
flag++;
}
tempLineData=sc.nextLine();
elements = tempLineData.split(" ");
ints.add((int)elements[0].trim());
floats.add((float)elements[1].trim());
}
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. When I enter something like "Hello World" and hit a new line I can only enter 3 more words. So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line.
Here is my code so far:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
According to the documentation, Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead.
Additionally, you can remove code duplication (which you always should do, keeping things DRY) by creating the array beforehand and allocating the user input entries within a loop:
final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);
String[] cars = new String[numberOfCars];
for (int i = 0; i < numberOfCars; i++) {
cars[i] = userInput.nextLine();
}
I recommend that you have a certain keyword or phrase that the user can type which stops the program. Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. Each value is stored in a java.util.ArrayList called "inputs." When the user is done entering input, he/she will type "stop" and the program will stop.
import java.util.*; //you need this for ArrayList and Scanner
public class Input{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in); //create a scanner object
ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
String temp = ""; //create a temporary string which will represent the current input string
while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the new input each iteration
inputs.add(temp); //add the temp string to the arraylist
}
}
}
If you want to convert the ArrayList to a normal String[], use this code:
String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
inputArray[i] = inputs.get(i);
}
You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. This why when you have more questions you can add them to list without changing anything else on the code.
Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]);
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<String> questions = new ArrayList<String>(5){{
add("What is your name?");
add("What is school you went to?");
add("Do you like dogs?");
add("What is pats name?");
add("Are you batman?");
}};
ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
String input = ""; // Stores user input here
Scanner scanner = new Scanner(System.in);
for(String question : questions){
System.out.println(question); // Here we adding a new line and the user type his answer on a new line
input = scanner.nextLine();
answers.add(input); // Store the answer on answers array
}
System.out.println("Thank you.");
String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
System.out.println("You entered: " + a.toString());
}
}
You want this instead:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
I'm just starting to learn Java and I'm trying to complete this exercise.
I've understood how to extract the information from the txt file (I think) using scanner (we're only supposed to change the method body). However I'm not sure of the correct syntax to transfer the information to an array.
I realise it must be very simple, but I can't seem to figure it out. Could someone please point me in the right direction in terms of syntax and elements needed? Thank you in advance!
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
public class Lab02Task2 {
/**
* Loads the game records from a text file.
* A GameRecord array is constructed to store all the game records.
* The size of the GameRecord array should be the same as the number of non-empty records in the text file.
* The GameRecord array contains no null/empty entries.
*
* #param reader The java.io.Reader object that points to the text file to be read.
* #return A GameRecord array containing all the game records read from the text file.
*/
public GameRecord[] loadGameRecord(java.io.Reader reader) {
// write your code after this line
Scanner input = new Scanner(reader);
for (int i=0; input.hasNextLine(); i++) {
String inputRecord = input.nextLine();
input = new Scanner(inputRecord);
// array?
}
return null; // this line should be modified/removed after finishing the implementation of this method.
}
}
In case you already have a String of the file content, you can say:
String[] words = content.split("\\s");
You can parse your String like this:
private ArrayList<String> parse(BufferedReader input) throws CsvException {
ArrayList<String> data = new ArrayList<>();
final String recordDelimiter = "\\r?\\n|\\r";
final String fieldDelimiter = "\\t";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(recordDelimiter);
while( scanner.hasNext() ) {
String line = scanner.next();
data.add(line);
}
return data;
}
The input text will be scanned line by line.
You can use an ArrayList<String>, like this:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
And if you want to get the value of some item of the ArrayList you just have to make reference with get function, like this:
list.get(//Here the position of the value in the ArrayList);
So, if you want to get all the values of the ArrayList you can use a loop to do it:
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
And finally close your Scanner:
s.close();
I expect it will be helpful for you!
Assuming your one row in file contains one game only
for (int i=0; input.hasNextLine(); i++) {
String inputRecord = input.nextLine();
input = new Scanner(inputRecord);
String line=input.nextLine();
arr[i]=line;
}
return arr;
Here are my directions:
This program will use two arrays - these are called parallel arrays. You will NOT be using an array of objects.
You will have a minimum of 6 methods in this application (including main())
inputData() - input from the data file into two arrays - the data file is below, call it "population.txt"
remember to check for the existence of the file before associating the Scanner object to it
displayCountries() - display all of the countries - just the countries
Can you please tell me why this will not run? I need to have the value of the population and the country name together so I can write it in a table later. So I am thinking that I need to read the first value into countryName and the first value into populationNum instead of reading them all in at the same time. The text that I am reading in is below the code. I do not know how to do that though. I am also wondering if I need the [25] when I instantiate. It gives me this error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Population.inputData(Population.java:32)
at Population.main(Population.java:13)
This is my code:
import java.io.*;
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Population{
public static void main(String [] args)throws IOException{
//Arrays
String [] countryNames = new String [25];
int [] populationNum = new int [25];
//Input data from file into the array
inputData(countryNames, populationNum);
//Displays and calculations
displayCountries(countryNames);
} //end main()
//this class gets the input for arrays from the file
public static void inputData(String [] countryNames, int [] populationNum) throws IOException{
File infile = new File("population.txt.");
int index = 0;
Scanner scan = new Scanner(infile);
while(scan.hasNext())
for(int i = 0; i < countryNames.length; i++)
countryNames[i] = scan.nextLine();
for(int i = 0; i < populationNum.length; i++)
populationNum[i] = scan.nextInt();
} //end inputData()
//this class displays the countries
public static void displayCountries(String [] countryNames) {
for(int i = 0; i < countryNames.length; i++)
System.out.println(countryNames[i]);
} //end displayCountries()
}//end class
Ghana
24333000
Brazil
193364000
Australia
23480970
Nigeria
170123000
Papua New Guinea
6888000
Mexico
108396211
Egypt
79221000
Iran
75078000
Myanmar
50496000
Belgium
10827519
Tuvalu
10000
russia
141927297
You need to read into both arrays in the same loop, like this:
int i = 0;
while(scan.hasNext()) {
countryNames[i] = scan.nextLine();
if (scan.hasNext()) populationNum[i] = scan.nextInt();
if (scan.hasNext()) scan.nextLine(); // Go to the next line
i++;
}
The two for loops inside the while are incorrect (not to mention that the second for loop is not even part of the while, because you omitted curly braces).
Demo.
You need { after while(scan.hasNext()) and closing } after two for loops. What is happening is while loop scans all data then the for loops try to do scan.next when the scanner is already at end of file. Hope this helps