I attempted a problem from codechef and made my code on java which runs perfectly on eclipse on my laptop.But everytime i try to submit the code it gives me this NZEC error.
Can anyone tell why am i getting the non zero exit code error (NZEC) while i am executing this code.
Problem to this code: https://www.codechef.com/problems/STRPALIN
import java.util.*;
import java.io.*;
public class Palindrome {
public boolean check() throws IOException{
String A;
String B;
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
A=inp.readLine();
B=inp.readLine();
for(int i=0;i<A.length();i++)
{
for(int j=0;j<B.length();j++)
{
if(A.charAt(i)==B.charAt(j))
return true;
}
}
return false;
}
public static void main(String[] args)throws NumberFormatException, IOException {
Palindrome M = new Palindrome();
boolean[] array = new boolean[10];
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for(int i=0;i<T;i++)
{
array[i]=M.check();
}
for(int j=0;j<T;j++){
if(array[j])
System.out.println("Yes");
else
System.out.println("No");
}
}
}
The problem with your code is that while taking input from user for String A and B, the readline() method returns null, and when you try to access String A or B, a NullPointerException is thrown. Hence the non-zero exit code .
Now, the readline() method returned null value because you created a BufferedReader object twice, which led to leakage of memory.
Refer to this link: readline() returns null in Java
Regarding the NZEC error:
import java.util.*;
import java.io.*;
class Codechef {
public boolean check() throws IOException{
String A;
String B;
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
A=inp.readLine();
B=inp.readLine();
for(int i=0;i<A.length();i++)
{
for(int j=0;j<B.length();j++)
{
if(A.charAt(i)==B.charAt(j))
return true;
}
}
return false;
}
public static void main(String[] args)throws NumberFormatException, IOException {
try {
Codechef M = new Codechef();
boolean[] array = new boolean[10];
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for(int i=0;i<T;i++)
{
array[i]=M.check();
}
for(int j=0;j<T;j++){
if(array[j])
System.out.println("Yes");
else
System.out.println("No");
}
} catch(Exception e) {
} finally {
}
}
}
Related
I came up with the following code to read information from a file:
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public void openFile() {
try {
s = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("File not found. Try again.");
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
public void closeFile() {
s.close();
}
}
However, I get a NullPointer error on the (while (s.hasNext())) line and can't find a solution.
I'm working in Eclipse and the file I'm reading from is imported correctly into the project so that should not be an issue.
EDIT:
The way I access the methods:
public class Tester {
public static void main(String[] args) {
Reader read = new Reader();
read.openFile();
read.readFile();
read.closeFile();
}
}
As per the statement where NPE throws, while (s.hasNext()), it's most probable that the s is null pointer, you can add System.out.println(s); before that statement to double confirm it.
And for the reason why the s is null, there are two possible reasons:
You didn't invoke openFile before readFile
Exception is thrown when you open the file. The s is only a declaration and hasn't pointed to any object yet.
Maybe for a better practice, you can assert whether a instance is null or not before invoking its method. And as per my understanding, the readFile depends on the result of openFile, maybe you can set return value of openFile like a boolean value and check the return value before further open file operation. It's impossible to read a file which can't be even open, right?
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public boolean openFile() {
try {
s = new Scanner(new File("file.txt"));
return true;
} catch (Exception e) {
System.out.println("File not found. Try again.");
return false;
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
}
The invoker can do something like below:
Reader reader = new Reader();
if (reader.openFile())
reader.readFile();
The line with "private static BufferedReader" is where the problem lies.
"-unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" is the error.
Here is my current code:
import java.io.*;
import java.util.*;
public class PG2ERC
{
private static ArrayList<Integer> arl = new ArrayList<Integer>();
private static BufferedReader br = new BufferedReader(new FileReader("pageRefString.txt"));
public static void main(String[] args) throws IOException, FileNotFoundException
{
String [] arr;
int n1 = 3;
int n2 = 4;
int f;
int pf1 = 0;
int pf2 = 0;
arr = br.readLine().split(" ");
for(String s:arr)
{
f=Integer.parseInt(s);
if(arl.contains(f))
{
arl.remove(arl.indexOf(f));
arl.add(f);
}
else if(arl.size() < n1)
{
++pf1;
arl.add(f);
}
else
{
arl.remove(0);
arl.add(f);
++pf1;
}
f=Integer.parseInt(s);
if(arl.contains(f))
{
arl.remove(arl.indexOf(f));
arl.add(f);
}
else if(arl.size() < n2)
{
++pf2;
arl.add(f);
}
else
{
arl.remove(0);
arl.add(f);
++pf2;
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("pg2out.txt"))))
{
writer.write(("Number of page faults is ") + pf1);
writer.write(("Number of page faults is ") + pf2);
}
}
}
}
The problem is more simply demonstrated like this:
import java.io.*;
class Test {
private static Reader reader = new FileReader("foo.txt");
}
The problem is that the static initializer for your class can throw an exception. That's entirely separate to your main method.
Now in your case, the simplest solution is to change your fields to local variables:
// No need to declare FileNotFoundException - it's a subclass of IOException anyway
public static void main(String[] args) throws IOException
{
ArrayList<Integer> arl = new ArrayList<Integer>();
BufferedReader br = new BufferedReader(new FileReader("pageRefString.txt"));
... rest of method as before ...
}
At that point, the code that can throw an exception is within a method that declares that those exceptions can be thrown, so it's fine.
If you do need to initialize static variables like this, you should do so in a static initializer block:
private static BufferedReader br;
static {
try {
br = new BufferedReader(new FileReader("pageRefString.txt"));
} catch (IOException e) {
// Go bang hard - RuntimeException isn't a checked exception
throw new RuntimeException(e);
}
}
Set your BufferedReader static variable to null outside the main method. and initialize in main method will fix the issue.
private static BufferedReader br = null;
public static void main(String[] args) throws IOException, FileNotFoundException
{
br = new BufferedReader(new FileReader("pageRefString.txt"));
I am doing this program on Reading characters and I have types as it is that is there in the book.But still I am getting exceptions.
package Applets;
import java.io.*;
public class BRead extends InputStream{
public static void main(String args[]){
throws IOException
{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter characters,'q' to quit");
do{
c=(char) br.read();
System.out.println(c);
}while(c!='q')
}
}
}
Can anyone tell mw why the exceptions are coming??
Your class extends InputStream so it need to implement the abstract method read. Moreover you have some syntax errors as well, the correct version will be like this
import java.io.*;
public class BRead extends InputStream {
public static void main(String args[]) throws IOException {
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter characters,'q' to quit");
do {
c = (char) br.read();
System.out.println(c);
} while (c != 'q');
}
#Override
public int read() throws IOException {
return 0; //change it as per your need
}
}
That is because you are doing many syntax errors in your code.
Please find the below code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BRead extends InputStream {
public static void main(String args[]) throws IOException {
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter characters,'q' to quit");
do {
c = (char) br.read();
System.out.println(c);
} while (c != 'q');
}
#Override
public int read() throws IOException {
// TODO Auto-generated method stub
return 0;
}
}
I'm having trouble just return the string of the color. For some reason it will not return the num. Not sure if I need to insert the end of the if statement with an else but I feel like that what the catch statement if for.
Main Class
package edu.computer.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Computer {
public Computer() {
}
public String getProcessor() {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(in);
String num = null;
System.out.println("Type red to print red or blue to print blue");
try {
num = keyboard.readLine();
if (num.equals("red"))
num = "red";
if (num.equals("blue"))
num = "blue";
} catch (IOException e) {
System.out.println("Exception occured!");
}
return num;
}
}
Test Class
package edu.computer.test;
public class ComputerTester {
public static void main(String[] args) {
Computer a = new Computer();
a.getProcessor();
}
}
Your code example works just fine. I added the following line to your test and it printed the colour as expected:
public static void main(String[] args) {
Computer a = new Computer();
System.out.println(a.getProcessor());
}
Prints blue or red as appropriate.
What I want to do: My class copytest reads a textfile, edits one character and save this new file in a new directory. I want to program a void-method out of it, which does exactly the same and can then be used the following way:
copy(String "C:\\Old.txt", String "C:\\New.txt", int 1, int 1)
Now copy does exactly the same as my old class copytest, it reads the old file, edits it and saves it.
My first idea was to have two files as the first to arguments, but this is obviously impossible. My new idea is to give the method two strings of the wanted directories of the old and the new file. It still doesn't work. I hope, you understand, what I want to do and how to solve this problem.
Old class code (works):
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("...old.txt");
Scanner scanner = new Scanner(file);
int lineNumber=1;
int charNumber=1;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("...new.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
New void code (first try with file as argument):
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
Scanner scanner = new Scanner(old);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File(new.getPath());
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
readFile();
}
New try with strings as argument, but still doesn't work:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class copytestnew {
public void copy(String old, String newone, int x, int y) {
// Location of file to read
File file = new File(old);
Scanner scanner = new Scanner(file);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file2 = new File(newone);
output = new BufferedWriter(new FileWriter(file2, true));
output.write(line);
output.write(newLine);
output.close();
i++;
}
scanner.close();
System.out.println("File copied");
}
}
I remember you! I answeared you last time on how to replace the char at one of the lines.
First, change the decleration to
public static void copy(String old, String newone, int x, int y) throws IOException {
NOTICE the throws statment!
And now when you want to call this method you should use it inside a try-catch block or declear that you throwing exception same as you did at the copy function.
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
You're defining a function inside a method. As all functions in java are methods (static or non-static), this is not permitted. Try this:
class IDontKnowHowToNameIt {
public static void copy(file old, file new, int x, int y) {
//...
// call readFile from here
// ...
}
private static void readFile() throws Exception {
//...
}
}