I'm coding a program that copy the contents of all the files to the last input file taken( all the files are given by the user at Command prompt). So, how can I declare an array that takes the size from the user?
Do it like that:
import java.util.Scanner; <-------- import the class
public class InputFromUser {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number for the array size:");
int size = scan.nextInt();
int[] arr = new int[size];
}
}
Either use java.io like this:
BufferedReader columnInput = new BufferedReader(new InputStreamReader (System.in));
int size = Integer.parseInt(columnInput.readLine());
If the list of files supplied when running the application as arguments : you can use the args.length property which returns the number of the supplied arguments:
public static void main(String[] args) {
System.out.println(args.length);
}
You can also do in this way :
public static void main(String args[]) {
BufferedReader input = new BufferedReader (new InputStreamReader(System.in));
try {
System.out.println("Enter a array size:");
int arraysize = Integer.parseInt(input.readLine());
int[] arr = new int[arraysize];
} catch (Exception e) {
e.printStackTrace();
}
}
Related
PS: all integers in the file are more than one digit.
I want to input a 1 x n matrix from a text file in a java program. I can input a matrix with single digit numbers by the following code, suggest solutions that would modify the same.
import java.util.*;
import java.io.*;
class New_data{
public int[][] allocation= new int[25][25];
public int[][] need= new int[25][25];
public int[][] max= new int[25][25];
public int[] available=new int[25];
public int rows=0,col=0;
int count_flag=0;
void input_avaliable()
{
System.out.println("Enter the available matrix\nDimensions: " + col+":1");
}
void readfile(String s,int arr[][]) throws IOException
{
File file= new File(s);
FileInputStream fis= new FileInputStream(file);
InputStreamReader isr= new InputStreamReader(fis);
BufferedReader br= new BufferedReader(isr);
String line;
int i=0,j=0;
int shift=0; //shift int is used to convert char array to int
char[] ch=new char [50];
while((line = br.readLine()) != null)
{
if(count_flag==0)
{
rows++;
col=(line.length());
col=col/2;
}
else{}
ch=line.toCharArray();
shift=0;
for(j=0;j<col;j++)
{
arr[rows-1][j]=ch[j+shift];
shift++;
}
}
count_flag=1;
br.close();
}
void need() throws ArrayIndexOutOfBoundsException
{
Scanner sc=new Scanner(System.in);
for(int i=0;i<rows;i++)
{
for(int j=0;j<=col;j++)
{
need[i][j]=max[i][j]-allocation[i][j];
}
}
}
}
class Bankers{
public static void main(String args[]) throws IOException
{
New_data Data=new New_data();
String location=new String("allocation.txt");
Data.readfile(location,Data.allocation);
location="max.txt";
Data.readfile(location,Data.max);
Data.need();
}
}
This code outputs two arrays properly, but fails when the input file do not have single digit integers.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've created a class with a few objects.
class SalesPerson {
String number;
String name;
double salesAmount;
}
So now I need to copy some data from a text file to an array.
"sales.txt"
S0001
Alice
2000
S0002
Bob
3400
S0003
Cindy
1200
S0004
Dave
2600
Below is the shortened version of my code, assuming that the getName(s), setName(s) and constructors are created and the text file can be successfully read:
class ArrayImport {
public static void main(String args[]) throws FileNotFoundException {
String fileName = "sales.txt";
SalesPerson sp = new SalesPerson[4]; //Manually counted
//Read the file
Scanner sc = new Scanner(new FileReader(fileName));
//Copy data to array
int i = 0;
while (sc.hasNext()) {
sp[i].name = sc.nextLine(); //Error starts here
sp[i].number = sc.nextLine();
sp[i].salesAmount = Double.parseDouble(sc.nextLine());
i++;
}
}
}
I get the error message "Exception in thread "main" java.lang.NullPointerException..." pointing to the line which I commented "Error starts here".
So I am guessing that this is not the way to assign a value to an object array, and if my guess is correct, what are the correct syntax?
The instance of object is null so you have to create the instance first. so create instance like this 'staff[i] = new SalesPerson();'
I added instance creation to your code.
class ArrayImport {
public static void main(String args[]) throws FileNotFoundException {
String fileName = "sales.txt";
SalesPerson sp = new SalesPerson[4]; //Manually counted
//Read the file
Scanner sc = new Scanner(new FileReader(fileName));
//Copy data to array
int i = 0;
while (sc.hasNext()) {
staff[i] = new SalesPerson();
staff[i].name = sc.nextLine(); //Error starts here
staff[i].number = sc.nextLine();
staff[i].salesAmount = Double.parseDouble(sc.nextLine());
i++;
}
}
}
Working example:
public class ArrayImport {
public static void main(String[] args) throws FileNotFoundException {
List<SalesPerson> persons = new ArrayList<>();
SalesPerson salesPerson = null; //Manually counted
//Read the file
Scanner scanner = new Scanner(new FileReader("sales.txt"));
int count=0;
while(scanner.hasNext()) {
if( count==0 || count%3 == 0) {
salesPerson = new SalesPerson();
salesPerson.setNumber(scanner.nextLine());
salesPerson.setName(scanner.nextLine());
salesPerson.setSalesAmount(Double.parseDouble(scanner.nextLine()));
persons.add(salesPerson);
count+=3;
}
}
persons.forEach(person->System.out.println(person.toString()));
}
}
What I'm trying to do is to make my program read input test-cases from a file instead of standard console input and write back the output to another file.
Here comes the problem into play, if I'm trying to give input using file it is showing java.lang.NullPointerException, but on other hand giving correct output if I'm trying to give custom standard input(using cmd) and printing output to a file.
Here is my sample program:
public class Roman
{
static private final String INPUT = "Q4.in";
static private final String OUTPUT = "Q4.out";
// open I/O files
public static void main(String[] args)
{
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
int i;
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
Num2Rom[] tc=new Num2Rom[T];
for(i=0;i<T;i++)
{ tc[i]=new Num2Rom(); }
System.out.println(T+"\n");
for(i=0;i<T;i++)
{ tc[i].display(i+1); }
}
}
and
ArrayList<String> wordList;
Num2Rom()
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String numeral = sc.nextLine();
System.out.println("print"+numeral);
numeral = numeral.toUpperCase();
String[] words = numeral.split(" ");
wordList = new ArrayList<>(Arrays.asList(words)); }
}
The input is formatted as:
2
Eight
Twenty
You can use java command line arguements to give input to the program.
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
do convert the arguments to the desired type,as arguments are received in the string format.
such as if you want an integere you can convert using
int value=Integer.parseInt($args[0]);
My task is to read from an input file test.txt, this text has some sentences.
I need to write a class with a constructor and three methods.
One of which has to reverse the order of the words in a sentence.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc3 = null ;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc3 = new Scanner (file);
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
// ArrayList<String> wordsarraylist = new ArrayList<String>();
while(sc3.hasNextLine()){
String sentence = sc3.nextLine();
// int length = sentence.length();
String[] words = sentence.split(" ");
// wordsarraylist.clear();
List<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.close();
}
}
}
I have removed two other methods but they don't interfere with this one.
And this is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.reverseEachLine(new File("out2.txt"));
}
}
The problem is that at the end of the execution my output file contains the same thing. It is not reversing the order. How come? doesn't Collections.reverse() reverse the order? And so when I print it I should have the words in reverse?
I am also required to use arraylist.
This my input file:
This is just a small file. That
has some lines of text.
If we are successful, these
lines will be
reversed.
Let's hope for the best!
I am supposed to get this in my output:
That file. small a just is This
text. of lines some has
these successful, are we If
be will lines
reversed.
best! the for hope Let's
But i am getting this:
This is just a small file. That
has some lines of text.
If we are successful, these
lines will be
reversed.
Let's hope for the best!
Try this code for the method reverseEachLine, it works fine. Don't construct Scanner at the constructor.
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
}
I have answered here with full code java cannot create file by 3 methods
I am trying to figure out how to make a program that reads data from a text file, and fills a Jtable with it, I will need to be able to search the table, and do some calculations with the numbers.
A row in the text file would contain:
name, country, gender, age, weight
The number of rows is unknown (I need to count the number of rows).
This is what I tried, but it seems to crash. I need to count the # of rows, and then fill the array with the content from the rows.
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()){rows++;}
Object[][] data = new Object[rows][5];
System.out.print(rows);
file.nextLine();
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
}
change your code as follows
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
try{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine())
{
rows++;
file.nextLine();
}
file = new Scanner (new File("data.txt"));
System.out.println(rows);
Object[][] data = new Object[rows][5];
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
You create an array with 0 rows and then you try to access the empty array dimension.
Also I suppose you should reset the pointer of the scanner after counting the rows.
ArrayList should be more useful for your goal.
class Person {
String name, country, gender;
int age;
double weight;
public Person(String n, String c, String g, int a, double w) {
name = n;
country = c;
gender = g;
age = a;
weight = w;
}
}
Would properly model your data better when you are extracting from the file (I took a guess at Person but call it what you will). We then use ArrayList like so:
public static void main (String[] args) throws IOException {
ArrayList<Person> people = new ArrayList<Person>();
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()) {
String str = file.nextLine();
String[] tokens= str.split(",");
people.add(new Person(tokens[0], tokens[1], tokens[2],
Integer.parseInt(tokens[3], Double.parseDouble(tokens[4]))));
}
file.close();
Person[] arrayPeople = people.toArray();
}
ArrayLists are far more powerful than arrays as you can perform all sorts of operations on them like sorts and searches and of course you don't have to worry about their initial size because they just grow as you add new elements.
Maroun is right, you really need to use some Collections to help you with that :
public static void main(String[] args) throws Exception {
List<String[]> lines = readFiles(new File("data.txt"));
String[][] data = lines.toArray(new String[0][]);
}
public static List<String[]> readFiles(File file) {
List<String[]> data = new LinkedList<>();
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split(",");
data.add(tokens);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return data;
}
Note that you can use some third party libraries like Commons IO to read the file's lines :
List<String> lines = org.apache.commons.io.FileUtils.readLines(new File("data.txt"));)
Less code = less bugs!
Hope it helps
Move this line
Object[][] data = new Object[rows][5];
below
System.out.print(rows);
But as per answers above, we suggest change the code to use array lists if possible.