How To Copy Values To Object Array [duplicate] - java

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

Related

I am getting Null pointer Exception input taking array buffereread [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
import java.util.Scanner;
import java.io.*;
class AraOfDigit{
public static void main(String[] args) throws IOException{
Scanner sc =new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter wr = new PrintWriter(System.out);
int iteration = sc.nextInt();
int count = 0;
while(count<iteration){
int n = sc.nextInt();
int mod = sc.nextInt();
String arr [] = new String[n];
****String[] arr_A =br.readLine().split(" ");****//Nullpointer Exception How to slove?
for(int i=0;i<n;i++) {
arr[i]=arr_A[i];
}
StringBuilder total = new StringBuilder();
for(int j=0;j<n;j++){
total.append(arr[j]);
}
int num = Integer.parseInt(total.toString());
num = num/10;
int op = num%mod;
System.out.println(op);
count++;
}
}
}
You are reading the next line when you have reached the end. So there's nothing to read anymore and you get null for br.readLine().
Take a look at Javadoc:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
You can check if a line is null:
String line = br.readLine();
if (line != null) {
String[] arr_A =.split(" ");
//...
}

How to map first row(attribute name) in excel file with the all cell values in java?

I have tried the following code to get first row of value(attribute name) in excel file mapping with other specific cell values i.e attribute-name=value (e.g age=30-39,meno-pause=premeno,.. etc). And then, the mapping values are add ArrayList.
But no correct output please help me!
attribute-name>> age,meno-pause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quard,irradiat,Class
-------***
Values>>
30-39,premeno,30-34,0-2,no,3,left,left_low,no,no-recurrence-events
40-49,premeno,20-24,?,no,2,right,right_up,no,no-recurrence-events
40-49,premeno,20-24,0-2,no,2,left,left_low,no,no-recurrence-events
60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
60-69,ge40,15-19,0-2,no,2,left,left_low,no,no-recurrence-events
50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
60-69,ge40,20-24,0-2,no,1,left,left_low,no,no-recurrence-events
40-49,premeno,50-54,0-2,no,2,left,left_low,no,no-recurrence-events
40-49,premeno,20-24,0-2,no,2,right,left_up,no,no-recurrence-events
Java Code
public class Excel {
private static Scanner sc;
public static void main(String[] args) throws FileNotFoundException {
List<String> transactions = new ArrayList<String>();
String str1,str2=null;
String addArray = null;
sc = new Scanner(new File("bc_dataset.csv"));
str1=sc.nextLine();
while (sc.hasNextLine())
{
String str2 = sc.nextLine();
transactions.add(str1 + "=" + str2);
System.out.println(transactions);
}
}
Check below changes. Explanation is in comments.
public class Excel {
private static Scanner sc;
public static void main(String[] args) throws FileNotFoundException {
List<String> transactions = new ArrayList<String>();
String str1,str2=null;
String addArray = null;
sc = new Scanner(new File("bc_dataset.csv"));
str1=sc.nextLine();
String []attributes = str1.split(","); // split the attributes by `,`. This will return array of String [age,meno-pause,tumor-size,...]
while (sc.hasNextLine())
{
String str2 = sc.nextLine();
String []linesplit = str2.split(","); // split the line by `,`. This will return array of String [30-39,premeno,30-34....]
// loop over both arrays and add them together
for(int i = 0; i<attributes.length; i++){
finalline = finalline+attributes[i]+"="+linesplit[i]+",";
}
// this will add extra `,` in the end of string which I leave on you to escape
transactions.add(finalline); // add final line to the list
System.out.println(transactions);
}
}

output is null in the console

it's showing null exception. what to do now?
import java.io.File;
import java.util.Scanner;
public class Quiz1 {
public static void main(String[] args) {
File f = new File("QuizMark.txt");
try{
Scanner s = new Scanner (f);
QuizMark[] p = new QuizMark[10];
while(s.hasNext()==true)
{
int c = s.nextInt();
double d = s.nextInt();
for(int i=0;i<10;i++){
p[i]= new QuizMark(c,d);
System.out.println(p[i].getId());
System.out.println(p[i].getScore());
i++;
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
First of all your file must define a pattern of data saved in it like marks and id Separated by commas or hyphens underscores etc whatever you like to save pattern.Each next data should be on next line.Then read the text in proper manner as you saved in file.
Example QuizMarks.txt
01,96.5
02,78.9
03,65
04,89.7
Java Code
int count = 0;
String s[];
String line="";
QuizMark[] p = new QuizMark[10];
BufferedReader br= new BufferedReader(new FileReader("QuizMark.txt"));
while(line=br.readLine()!=null){
s=line.split(",");//your data separated by symbol in file
//First Record with id and marks
int id =Interger.parseInt(s[0]); //conversion from string to int
double marks = Double.parseDouble(s[1]); //conversion from string to double
p[count]= new QuizMark(id,marks);
count++;
}

Loading elements of Array into a collection

I have a text file of names( last and first). I have successfully been able to use RandomAccessFile class to load all the names into an Array of strings. What is left for me to do, is to assign each of the first names to an Array of first names and each of the last names in the list to an array of Last Names. Here is what I did but Im not getting any desired result.
public static void main(String[] args) {
String fname = "src\\workshop7\\customers.txt";
String s;
String[] Name;
String[] lastName, firstName;
String last, first;
RandomAccessFile f;
try {
f = new RandomAccessFile(fname, "r");
while ((s = f.readLine()) != null) {
Name = s.split("\\s");
System.out.println(Arrays.toString(Name));
for (int i = 0; i < Name.length; i++) {
first = Name[0];
last = Name[1];
System.out.println("last Name: " + last + "First Name: "+ first);
}
}
f.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Please help me out I seem to be confused on what kind of collection to use and how to go about it Thanks
You could create a method to read a file and put the data in an Array, but, if you are determined to use an Array you are going to have to create it at a fixed size b/c arrays are immutable in java
public class tmp {
public static void main(String[] args) throws FileNotFoundException {
//problem you have to create an array of fixed size
String[] array = new String[4];
readLines(array);
}
public static String[] readLines(String[] lines) throws FileNotFoundException {
//this counter can be printed to check the size of your array
int count = 0; // number of array elements with data
// Create a File class object linked to the name of the file to read
java.io.File myFile = new java.io.File("path/to/file.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(myFile);
/* This while loop reads lines of text into an array. it uses a Scanner class
* boolean function hasNextLine() to see if there another line in the file.
*/
while (infile.hasNextLine()) {
// read a line and put it in an array element
lines[count] = infile.nextLine();
count++; // increment the number of array elements with data
} // end while
infile.close();
return lines;
}
}
However, the preferred method is to use an ArrayList which is an object that uses dynamically resizing arrays as data is added. In other words, you don't need to worry about having different size text files.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
String str;
ArrayList<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
A little about random access.
Classes like BufferedReader and FileInputStream use a sequential process of reading or writing data. RandomAccess, on the other hand, does exactly as the name implies, which is to permit non-sequential, random access to the contents of a file. However, Random access is typically used for other applications like reading and writing to zip files. Unless you have speed concerns I would recommend using the other classes.
public static void main(String[] args) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
String str;
String names[];
List<String> firstName = new ArrayList();
List<String> lastName = new ArrayList();
try {
while ((str = in.readLine()) != null) {
names = str.split("\\s");
int count = 0;
do{
firstName.add(names[count]);
lastName.add(names[count+1]);
count = count + 2;
}while(count < names.length);
}
} catch (IOException e) {
e.printStackTrace();
}
// do whatever with firstName list here
System.out.println(firstName);
// do whatever with LastName list here
System.out.println(lastName);
}

Reversing arraylist not working properly

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

Categories

Resources