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(" ");
//...
}
Related
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()));
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{//BigInteger bi1, bi2, bi3;
long t,j,n;
int i,x;
BigInteger u,sum,temp,m;
BigInteger[] a=new BigInteger[100009]; long[] b=new long[100009];
long mm=1000000007,f;
Scanner har=new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
t=har.nextInt();
for(f=0;f<t;f++)
{ temp = BigInteger.valueOf(1); sum = BigInteger.valueOf(0); u = BigInteger.valueOf(0);
n=har.nextInt(); x=har.nextInt(); m=har.nextBigInteger();//String line = br.readLine();
//String line = br.readLine(); // to read multiple integers line
//String[] strs = line.trim().split("\\s+");
//String[] s1 = br.readLine().split(" ");
//StringTokenizer st = new StringTokenizer(br.readLine());
for(i=1;i<=n;i++)
{b[i]=har.nextInt();
// b[i] = Integer.parseInt(st.nextToken());
//b[i] = Long.parseLong(System.console().readLine());
//b[i]=Long.parseLong(s1[i-1]);
}
}
}
}
input is of form
t
n x m
a[1] a[2] a[3] .......a[n]
This code is running correctly for scanner but if i try to use buffered reader or string tokenizer it is giving runtime error .
I am new to java and i need to use big integer for further part of the question.
There is nothing wrong with your code. You are defining the BufferReader as BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); and reading String as br.readLine();.
This snippet works absolutely fine and prints the input string back to the console:
public static void main (String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(br.readLine());
}
Some of the possibilities where you can get errors:
StringTokenizer
StringTokenizer st = new StringTokenizer(br.readLine());
Before passing it to the StringTokenizer make sure that you get a String back from br.readLine().
String text = br.readLine();
if(!StringUtils.isEmpty(text)) {
StringTokenizer st = new StringTokenizer(br.readLine());
/* Rest of the code */
}
Loop Condition Variable
for(i=1;i<=n;i++)
I do not see anything for BufferedReader which initializes n. Make sure you initialize it correctly.
Here is a quick code snippet:
public static void main (String[] args) throws Exception
{
long j, n, f, mm = 1000000007;
int i, x;
BigInteger u, sum, temp, m;
BigInteger[] a = new BigInteger[100009]; long[] b=new long[100009];
Scanner har = new Scanner(System.in);
long t = har.nextInt();
for(f=0;f<t;f++)
{
temp = BigInteger.valueOf(1);
sum = BigInteger.valueOf(0);
u = BigInteger.valueOf(0);
n = har.nextInt();
x = har.nextInt();
m = har.nextBigInteger();
/* Goto Next Line */
har.nextLine();
/* Start Reading Line */
String text = har.nextLine();
System.out.println("String Value: " + text);
if(null != text) {
StringTokenizer st = new StringTokenizer(text);
for(i = 1; i <= n; i++)
{
b[i] = Integer.parseInt(st.nextToken());
System.out.println("Value of b[" + i + "] = " + b[i]);
}
}
}
}
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 7 years ago.
I have a txt that is something like this:
Jhon 113
Paul 024
David 094
Peter 085
and from each line i want to have 2 variables one of the type string for the name and one int for the number
I wrote this code and what it does its take what ever a line says and ands it to an array called names but i will like to khow how to split the line into two different variables.
import java.io.*;
public class Read {
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("test.txt");
BufferedReader reader = new BufferedReader(file);
String names[] = new String[10];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
names[i] = line;
}
}
}
}
You should use split() :
String names[] = new String[10];
int numbr[] = new int[10];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
names[i] = line.split(" ")[0];
numbr[i] = Integer.parseInt(line.split(" ")[1]);
}
}
Ref : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
It is as intuitive as using the word split in your question. String class has a split function to split strings using a given parameter.
import java.io.*;
public class Read {
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("test.txt");
BufferedReader reader = new BufferedReader(file);
String names[] = new String[10];
int num[] = new int[10];
String lineSplit[] = new String[2];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
//splits line using space as the delimeter
lineSplit = line.split("\\s+");
names[i] = lineSplit[0];
num[i] = Integer.parseInt(lineSplit[1]);
}
}
}
}
I have been given a text file which reads:
aaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbb
ccccccccccccccccccc
ddddddddddddddddddd
and I have to make the program display it in the this order:
ddddddddddddddddddd
ccccccccccccccccccc
bbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaaaaa
So far this is my code:
public class LineReverserMain {
public static void main(String[] args) throws FileNotFoundException
{
int lineCount = 0;
ArrayList <String> LinesArray = new ArrayList<String>( );
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name: ");
String filename = in.next();
File file = new File(filename);
Scanner inFile = new Scanner(file);
while (inFile.hasNextLine()){
lineCount += 1;
String CurrentLine = inFile.nextLine();
LinesArray.add(CurrentLine);
}
System.out.println(LinesArray);
System.out.println(lineCount + " lines");
for(int linesCount = lineCount; linesCount>=0; linesCount = linesCount - 1){
System.out.println(LinesArray.get(linesCount));
}
}
}
But this doesn't seem to work.
The problem is your for loop at the end. At this time, lineCount is how many lines you have, but a valid index for your ArrayList is between 0 and lineCount - 1, inclusive. You must be getting an IndexOutOfBoundsException.
Start your linesCount variable one below lineCount. Change
for(int linesCount = lineCount; linesCount>=0; linesCount = linesCount - 1){
to
for(int linesCount = lineCount - 1; linesCount>=0; linesCount = linesCount - 1){
It's a classical problem you can solve with a stack:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;
public class LineReverserMain {
public static void main(String[] args) throws IOException {
// Linecounter and stack initialization
int lineCount = 0;
Stack<String> stack = new Stack<String>();
// Scaner and Filereader initialization
Scanner s = new Scanner(System.in);
System.out.print("Please enter the file name: ");
String filename = s.next();
File file = new File(filename);
// Push every read line onto the stack
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
stack.push(in.readLine());
lineCount++;
}
// While the stack isn't empty get the top most element
while (!stack.isEmpty())
System.out.println(stack.pop());
System.out.println(lineCount);
// Close the Scanner and FileReader
s.close();
in.close();
}
}
The stack hast a FILO structure, so you can just save String on it and pop them afterwards and get the correct order. Maybe you are interested in this shorter solution.
For my assignment, I have to read from a file with 25 numbers, then sort it in order, then write it to another file. I can't think of a way to pass the array in my code (to the the string of an array) to write the file in order and for it to write the numbers to a different file.
This is probably a simple question but I am just having a little trouble trying to pass everything.
Thank you in advance.
public static void main(String[] args) throws IOException{
int[] number;
number = processFile ("Destination not specified");
swapIndex(number);
writeToFile ("Destination not specified");
}
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int i = 0;
int[] value = new int [25];
while ( (line = inputReader.readLine()) != null){
int num = Integer.parseInt (line); // Convert string to integer.
value[i] = num;
i++;
System.out.println (num); // Test
}
inputReader.close ();
return value;
// Read the 25 numbers and return it
}
public static void swapIndex (int[] num){ // BUBBLE sort
boolean order = true;
int temp;
while (order){
order = false;
for (int i = 0; i <num.length-1; i++){
if (num[i]> num[i+1]){
temp = num[i]; //set index to temp
num[i] = num [i+1]; // swap
num[i+1]= temp; //set index to the higher number before it
order = true;
}
}
}
} // Method swapIndex
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write (String.valueOf ()); // Need to take the string value of the array
outputWriter.flush();
outputWriter.newLine ();
}
I would do it this way
Set<Integer> set = new TreeSet<Integer>();
Scanner sc = new Scanner(new File("1.txt"));
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
sc.close();
PrintWriter pw = new PrintWriter(new File("2.txt"));
for (int i : set) {
pw.println(i);
}
pw.close();
Instead of swapIndex(number) you used to sort the integer array, you could use Arrays.sort(number) and then pass this integer array(number) as one of the arguments to writeToFile method, iterate over those elements of integer array(number) and can add to the file.