I was working on one of the problems on codechef.com https://www.codechef.com/problems/ENTEXAM
Here is my solution for the problem-
import java.io.*;
class Entrance_Final
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static int test_case=0;//Test cases
static int students=0;
static int qualifiers=0;
static long result=0;
static int exams=0;
static long max_marks=0;
static long[]sigma_res;
static long sergey_score=0;
public static void main(String[]args)throws IOException
{
try
{
//System.out.println("Enter number of test cases.");
test_case=Integer.parseInt(in.readLine());
for(int lv=1;lv<=test_case;lv++)
comp_min_marks();
}
catch(Exception e)
{
System.err.println(e);
}
}
public static void comp_min_marks()throws IOException
{
try
{
//System.out.println("Enter students,enrollees,exams and maximum marks.");
String a=in.readLine();
a=a.trim();
int flag=0;
int times=1;
for(int lv=0;lv<a.length();lv++)
{
if(a.charAt(lv)==' '&&(times==1))
{
students=Integer.parseInt(a.substring(0,lv));
flag=lv+1;
times++;
}
else if(a.charAt(lv)==' '&&(times==2))
{
qualifiers=Integer.parseInt(a.substring(flag,lv));
flag=lv+1;
times++;
}
else if(a.charAt(lv)==' '&&(times==3))
{
exams=Integer.parseInt(a.substring(flag,lv));
flag=lv+1;
times++;
max_marks=Long.parseLong(a.substring(flag));
break;
}
}
sigma_res=new long[students-1];
//System.out.println("Enter the marks of all the students during their exams,each ones in one line");
for(int lv=0;lv<students-1;lv++)
{
String b=in.readLine();
sigma_res[lv]=int_sum(b);
}
//System.out.println("Now enter Sergey's scores");
if(exams==1)
{
//String b=in.readLine();
sergey_score=0;
}
else
{
String b=in.readLine();
sergey_score=int_sum(b);
}
sigma_res=doQuickSort(0,students-2);
result=sigma_res[students-qualifiers-1]-sergey_score+1;
if(result<0)
System.out.println("0");
else if(result<=max_marks)
System.out.println(result);
else
System.out.println("Impossible");
}
catch(Exception e)
{
System.err.println(e);
}
}
public static long int_sum(String b)throws IOException
{
try
{
b=b.trim();
long res=0;
int flag=0;
for(int lv=0;lv<b.length();lv++)
{
if(b.charAt(lv)==' ')
{
res+=Long.parseLong(b.substring(flag,lv));
flag=lv+1;
}
}
res+=Long.parseLong(b.substring(flag));
return res;
}
catch(Exception e)
{
System.err.println(e);
return -1;
}
}
private static long[] doQuickSort(int low,int high)throws IOException
{
try
{
if(high-low<1)
return sigma_res;
int wall=low;
int pivot_pos=(int)(Math.random()*(high-low))+low;
long pivot=sigma_res[pivot_pos];
long temp=sigma_res[high];
sigma_res[high]=pivot;
sigma_res[pivot_pos]=temp;
pivot_pos=high;
for(int lv=low;lv<=high-1;lv++)
{
if(pivot>sigma_res[lv])
{
temp=sigma_res[lv];
sigma_res[lv]=sigma_res[wall];
sigma_res[wall]=temp;
wall++;
}
}
temp=sigma_res[wall];
sigma_res[wall]=pivot;
sigma_res[pivot_pos]=temp;
pivot_pos=wall;
doQuickSort(low,wall-1);
doQuickSort(wall+1,high);
return sigma_res;
}
catch(Exception e)
{
System.err.println(e);
return sigma_res;
}
}
}
As you have probably noticed, I have enclosed all the code within my program in rather redundant try-catch blocks returning arbitrary exceptions. This is because I am always getting an NZEC-Error for my code (when I submit it online) and despite using these blocks, the error is persisting. I have repeatedly had a look at the constraints of the problem but had no luck figuring out what the issue is.
P.S I do not have access to the test cases of this problem.
Since there is no response here and I was able to figure out the issue, I suppose I might as well as answer my question. So first of all there was no exception at all, instead I was getting a VirtualMachineError in the line
sigma_res=new long[students-1];
(No idea why this was happening,all I know is the value of 'students' exceeded its constraint-defined limits).
After looking at a few solutions, I figured the issue was caused by taking the println statements out of the main() method and placing them in another one.
The moment I put the println statement back into main(), the solution was accepted.
P.S I still don't know why the program wouldn't terminate when the println statements where in another method.
Related
I am trying to create a loading sequence of 3 dots that repeats itself until input from the user breaks the loading sequence specifically the enter key. i connot for the life of me get the infinite while loop to end with input
public class loop {
public static void AnyKey() {
try {
System.in.read();
loading(false);
} catch (Exception e){}
}
public static void pause(long duration) {
try{
Thread.sleep(duration);
} catch (InterruptedException e){}
}
public static void loading(boolean status){
if (status == true) {
while (status) {
pause(500);
int i;
for (i = 0; i <3; i++){
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
}
public static void main(String[] args) {
loading(true);
AnyKey();
}
}
In your current code, the main method calls loading and never leaves the function. If you go through loading(true) step by step, you find that since while(status) is always true you are stuck there and AnyKey() is never called.
Also, System.in.read(); is a blocking call. This means that you will wait for user input but will be unable to print the '...'. Instead I recommend your read the documentation for input stream, there you will find the .read() function but also the .available() function which will let you know if any characters have been entered in the input buffer.
Those should be all the tools you need to figure this one out (I think).
Hope this helps!
I figured it out i needed to learn about and use Threads and global variables check out my code below im fairly pleased with myself i was working on this for 3 days now lol
import java.util.Scanner;
class AnyKey extends Thread {
public void run() {
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
loadingDots.loadingStatus = false;
}
}
public class loadingDots {
public static boolean loadingStatus;
public static void pause(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {}
}
public static void loading(){
loadingStatus = true;
while (loadingStatus) {
pause(500);
int i;
for (i = 0; i < 3; i++) {
if (!loadingStatus){
break;
}
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
public static void main(String[] args) {
AnyKey anykey = new AnyKey();
anykey.start();
loading();
}
}
To my understanding following code should print 0 as output because stack is full and it should get out of method immediately.
However when I ran the following code it is printing 100 for first case and prints 1 for second case:
class ErrorAndException {
public static int callStackOverflow() {
try {
callStackOverflow();
return 100;
} catch (Error e) {
System.out.println(e);
return 0;
} finally {
}
}
public static void main(String[] args) {
System.out.println(callStackOverflow());
}
}
Case - 2
class ErrorAndException {
public static int callStackOverflow() {
try {
callStackOverflow();
return 100;
} catch (Error e) {
System.out.println(e);
return 0;
} finally {
return 1
}
}
public static void main(String[] args) {
System.out.println(callStackOverflow());
}
}
Please help me understand this behavior.
Only the final call to callStackOverflow() (the one in which StackOverflowError is thrown) returns 0. But when it returns, the previous calls to callStackOverflow() all return 100. Your main method prints just the value returned by the initial call to callStackOverflow(), which is 100.
If you want the 0 to be returned to the main method, callStackOverflow() would have to return the value returned by the recursive call:
public static int callStackOverflow() {
try {
return callStackOverflow();
} catch (Error e) {
System.out.println(e);
return 0;
} finally {
}
}
The final item that causes the overflow will return 0 to the previous instance, but that value is lost as all lower instances just return 100 to one another until the final instance exits returning 100.
Instead of the try{}catch(Exception e){} method, is there a way to just state a custom message that replaces the exception message when exceptions like InputMismatchException, NoSuchElementException etc. occurs anywhere on the program?
EDIT: I want another method because if I use try{}catch(Exception e){} method than I will have to do it everywhere and the code also becomes longer.
For example:
public static String genderOutput()
{
try
{
System.out.print("\nMale - 1 \nFemale - 2 \n\nEnter either 1 or 2: ");
int genderInput = userInput.nextInt();
if(genderInput == 1)
{
String userGender = "Mr.";
return userGender;
}
else if(genderInput == 2)
{
String userGender = "Mrs.";
return userGender;
}
else
{
String userGender = " ";
return userGender;
}
}
catch (Exception e)
{
return null;
}
}
I have this function, now if there were multiple functions in a class like this then I would have to have the try{}catch(Exception e){} method everywhere. Wouldn't it be more efficient if you can just replace the exception message with your own and when such exception occurs which has a custom message stated to them then it would just throw out the custom message instead. This way, the code will be shorter as well.
SOLUTION TO MY PROBLEM:
public class Test
{
public static Scanner userInput = new Scanner(System.in);
public static String titleName = "TheRivalsRage";
public static String exitLevelMessage = "Program exited!";
public static String errorMessageTitle = "\n[Error] ";
public static String intInputMismatchException = "Please enter an Integer Value!";
public static String intNoSuchElementException = "Please enter either '1' or '2' without the quotes!";
public static String lineNoSuchElementException = "Please enter something!";
public static String bothIllegalStateException = "Scanner closed unexpectedly!";
public static void main(String[] args)
throws Exception
{
String usernameOutput;
String userGender;
try
{
System.out.print("Enter your username: ");
usernameOutput = userInput.nextLine();
userGender = genderOutput();
userInput.close();
}
catch(IllegalStateException e)
{
throw new IllegalStateException(errorMessageTitle + bothIllegalStateException);
}
if(userGender == null)
{
noSuchElementException();
}
else
{
System.out.println("\nWelcome " + userGender + " " + usernameOutput + " to " + titleName);
}
}
public static String genderOutput()
{
String userGender;
int genderInput;
System.out.print("\nMale - 1 \nFemale - 2 \n\nEnter either 1 or 2: ");
try
{
genderInput = userInput.nextInt();
}
catch(InputMismatchException e)
{
genderInput = 0;
inputMismatchException();
}
if(genderInput == 1)
{
userGender = "Mr.";
}
else if(genderInput == 2)
{
userGender = "Mrs.";
}
else
{
userGender = null;
}
return userGender;
}
public static void inputMismatchException()
throws InputMismatchException
{
throw new InputMismatchException(errorMessageTitle + intInputMismatchException);
}
public static void noSuchElementException()
throws NoSuchElementException
{
throw new NoSuchElementException(errorMessageTitle + intNoSuchElementException);
}
}
don't handle exception in each and every method just use throws Exception after method signature and handle it at end where the methods are being called.
and there in catch block you can throw your custom exception.
void method1() throws Exception{
//
}
void method2() throws Exception{
//
}
void finalmethod(){
try{
method1();
method2();
}catch(InputMismatchException e){
throw customExcpetion("custommessage1");
}catch(Exception e){
throw customExcpetion("custommessage2");
}
}
You need a try/catch.
However, you do not need to catch all exceptions separately, because the exceptions that you mention are all subclasses of RuntimeException. Hence, it is sufficient to make a single try/catch in your main to intercept RuntimeException, and print the replacement message:
public static void main(String[] args) {
try {
... // Actual code
} catch (RuntimeException ex) {
System.err.println("A runtime error has occurred.");
}
}
You can try Aspectj or Spring aop by creating around advice. You can replace message by catching exception inside advice and rethrow.
Check http://howtodoinjava.com/spring/spring-aop/aspectj-around-advice-example/
To know about how to use spring aop for anound advice
Java doesn't provide this feature out of the box but nobody prevents you to create a class that composes a Scanner object and that decorates methods that you are using as nextInt().
Inside the decorated method, invoke nextInt(), catch the exception that it may throw and handle it by returning null as in your question.
If it makes sense, you could even provide a nextInt() method with a default value as parameter if the input fails.
public class MyCustomScanner{
private Scanner scanner;
...
public Integer nextInt(){
try{
return scanner.nextInt()
}
catch(InputMismatchException e){
myStateObj.setErrorMessage("....");
return null;
}
}
public Integer nextInt(Integer defaultValue){
try{
return scanner.nextInt()
}
catch(InputMismatchException e){
myStateObj.setErrorMessage("....");
return defaultValue;
}
}
}
Now you can use the class in this way :
MyCustomScanner scanner = new MyCustomScanner();
Integer intValue = scanner.nextInt();
Integer otherIntValue = scanner.nextInt(Integer.valueOf(4));
I want to create a program that can relaunch itself if they detected any exception error during the execution.
Let say my program is trying reading a file. If the program failed to read a file, then it will have FileNotFound exception. After this exception occur, the program itself will restart and retry it again. This process will continue 3 times and if the program still cannot read that file, the program will then terminated and an exception message will be printed.
I created the read file part, but I have trouble to restart my program if it detect an error. Any help will be appreciated. I have included my pesudo code of what I am trying to do in the relaunch method.
fileReader.java
private static final int MAX_RETRIES = 3 ;
private static final int WAIT_BETWEEN_RETRIES_SEC = 30 ;
public static void main(String... args)
{
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
//this method is okay, good. pass to next method.
readFile();
//error detected, retry only this method. Error fixed, pass to next method
method2();
//error detected, retry only this method. Error fixed, pass to next method
method3();
method4();
method5();
break;
} catch (IOException e) {
e.printStackTrace();
retry++;
try {
Thread.sleep(WAIT_BETWEEN_RETRIES_SEC * 1000);
} catch (InterruptedException e1) {}
}
}
if (retry == MAX_RETRIES) {
System.out.println("Failed!");
return;
}
// success
}
private static void readFile() throws IOException {
//read file code
}
instead of relaunching, you can (and should) handle this in main(). For example:
private static final int MAX_RETRIES = 3 ;
private static final int WAIT_BETWEEN_RETRIES_SEC = 30 ;
public static void main(String... args)
{
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
readFile();
break;
} catch (IOException e) {
e.printStackTrace();
retry++;
try {
Thread.sleep(WAIT_BETWEEN_RETRIES_SEC * 1000);
} catch (InterruptedException e1) {}
}
}
if (retry == MAX_RETRIES) {
System.out.println("Failed!");
return;
}
// success
}
private static void readFile() throws IOException {
//read file code
}
Please try to use FutureTask under package java.util.concurrent. This support the feature the one you are looking for.
You don't have to restart the whole application after unsuccesfully reading a file - just re-run the problematic function (readFile() in this case).
Simply put readFile() in your reLaunch() function
private static void reLaunch(int relaunchAttempt){
readFile();
}
Or
private static void readFile(){
try{
//read file code
}catch(FileNotFoundException e){
//relaunch the application if error detected
readFile(count);
e.printStackTrace()
}
}
Maintain count in readFile() function
public class fileReader {
private static final MAX_RETRY = 3;
public static void main (String[] args){
int retry = 0;
while (retry++ < MAX_RETRY) {
try {
readFile();
break; // Break while loop
} catch (Exception e) {
if (retry == MAX_RETRY) {
// Failed 3 times
return;
}
}
}
// Success!
method1();
method2();
method3();
}
private static void readFile(){ ... }
private static method1(){ ... }
private static method2(){ ... }
private static method3(){ ... }
}
public class abc{
public static void main(){
try{
int a =10;
if(a=10){
throw new Exception();
}
l1:System.out.println(a);
}catch(Exception e){
continue l1;
}
}
}
Actually what I am trying to do is when an exception occurs I wish to continue the next statement after that as well.
Is there any way I can achieve it with Java?
You would just want to put System.out.println(a); in the catch block.
Putting it in a finally block would mean that it is executed even when an exception does not occur. The program only goes to the catch block when an exception occurs.
I think this is what you want?
public static void main(String[] args) {
int a = 9;
try {
if (a == 10) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace(); // only if there is any exception
} finally {
System.out.println(a); // always print this message
}
}
Or if a is 10
public static void main(String[] args) {
int a = 10;
try {
if (a == 10) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace(); // only if there is any exception
} finally {
System.out.println(a); // always print this message
}
}
try some thing like
int a =0;
try{
a =10;
if(a=10){
throw new Exception();
}
} catch(Exception ex){
//do nothing
} finally {
l1:System.out.println(a);
}
Anyway in java avoid jumping