If keep receiving runtimeException - java

The following code works fine with the eclipse but then in online editor I keep receiving runtimeException(NoSuchElementFoundException) please help me where am I going wrong?
{I have used sieve of eratosthenes alogirthm to find prime number in required range by the user}
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if(sc.equals(""))
{
sc.close();
}
Integer t = sc.nextInt();
while(t>0)
{
int m = sc.nextInt();
int n = sc.nextInt();
int prime[]= new int[n+1];
for(int i=0;i<=n;i++)
{
prime[i]=1;
}
prime[0]=0;
prime[1]=0;
for(int i=2;i<Math.sqrt(n);i++)
{
if(prime[i]==1)
{
for(int j=2;i*j<n;j++)
{
prime[i*j]=0;
}
}
}
for(int i=m;i<n;i++)
{
if(prime[i]==1)
{
System.out.println(i+" ");
}
}
System.out.println();
t--;
}
}
}

I tried your code over the site you mentioned. I changed the class visibility to be default to avoid some compilation error. It produced internal error with no further details and it suggested to test the code on https://ideone.com/ site. I used the sample test case and it passed successfully on ideone site..I suggest that you use hacker rank, I think it is more handy. In hacker rank you can unlock test cases to trace errors, bugs in your code, also you can have discussion with colleagues there over the problem. On the other hand I couldn't get the exception you mentioned "NoSuchElementFoundException" if you have detailed stack trace kindly include it and I shall update my answer accordingly.

Related

On the Codechef aug long challenge, AUG21C >CHFINVNT, this is the code I wrote, but the submit doesn't work. Its showing RE(NZEC) error

On the Codechef August long challenge, AUG21C > CHFINVNT, this is the code that I wrote, but the submit doesn't work. It's showing RE(NZEC) error.
The output still works.... but it won't submit. Please help.
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scr = new Scanner(System.in);
try {
int T = scr.nextInt();
while(T-- > 0)
{
int N = scr.nextInt();
int p = scr.nextInt();
int K = scr.nextInt();
int[] A = new int[N];
for(int i=0; i<N; i++)
{
A[i%K]++;
}
int sum=0;
for(int i=0; i<p%K; i++)
{
sum+=A[i];
}
int add = (p - (p%K)) / K;
add++;
sum = sum + add;
System.out.println(sum);
}
}catch(Exception e){}
}
}
Obviously, you have a flaw in your code. NZEC means non-zero exit code. Your code probably triggered an uncaught exception. Although you have a broad catch statement, there are exceptions outside of your catch clause.
In the question statement, N can be as large as 10^9.
If that happens, int[] A = new int[N]; tries to allocate that memory. That is over the memory constraints. Probably that is causing the problem. Even if you could allocate that memory, you would hit the time limits: even counting to 10^9 shall fail on CodeChef.
Not directly related to the question, but I want to comment on your code from the perspective of software engineering and competitive coding best practices.
Having a broad catch block will hide any exceptions you may have. Even if you get an index-out-of-bounds exception, you shall not be able to see that in your trials. You may avoid catching broad exceptions.
Your code does not have a proper indentation. That makes reading & debugging cumbersome. Especially in competitive programming, speed is important. So, a proper indentation is critical in that regard. You may just use an IDE to format the code.
Your Java code does not follow the general conventions of Java. One of the rules is "local variables start with a lowercase". The local variables A and N violate that rule.
The code you submitted contains many empty lines. While submitting your code to StackOverflow, removing unnecessary lines shall ease the reading and increase the probability of getting a good answer.

Unable to pass all conditions on codechef problem TREE2

please can someone check and tell why this code is unable to pass the 80% condition.
This problem is presented on the CodeChef with the problem code TREE2. It is problem in the beginner section.
There are 2 tasks. with the following code I am able to pass the task of 20%, but I am unable to pass the second task which consists of 80%.
Please look into it and suggest what went wrong.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
int t,n,h;
Scanner s=new Scanner(System.in);
t=s.nextInt();
while(t-- > 0)
{ h=0;
n=s.nextInt();
int [] arr=new int [n];
for(int i=0;i<n;i++)
arr[i]=s.nextInt();
Arrays.sort(arr);
while(true)
{
if(arr[n-1]==0)
break;
h++;
if(arr[0]==arr[n-1])
break;
for(int i=n-2;i>=0;i--)
{
if(arr[i]!=arr[n-1])
{
for(int j=i;j<n;j++)
arr[j]=arr[i];
break;
}
}
}
System.out.println(h);
}
}
}
its cause of time complexity.
you are using 4 loops.
that results in n raise to 4 time complexity.
try to solve using only one loop or without loop.
for hint go through SET concept

Create bubble sort code, but facing some errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Had a problem with compilation, getting error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at practise.code.main(code.java:11)
Here is my code:
package practise;
public class code {
static int number[]={1,8,5,9,4,7};
static int c[] = new int[number.length];
static int p=0;
static int q;
public static void main(String[] args){
change(number);
System.out.println("Array Before Bubble Sort");
for(int y: c){
System.out.print(y + "\t");
}
}
public static void change (int x[]){
for(int a: x){
for(int i=0; i<=x.length; i++){
if(a > x[i]){
continue;}
else {
p++;}
q = x.length - p - 1;
c[q] = a;
}
}
}
}
}
Some meta-help for future reference:
Compiler errors: these are when you experience an error that occurs at compile time. For Java, this is when you use javac, and your Java code is being turned into bytecode files for interpretation later.
Runtime errors: this is when you experience an error that occurs when you run your code. For Java, this is when you use java, and your Java code is being run.
If you find the two confusing, add into your question the thing you typed in order to experience the error. Specify all the flags and options you used, and format it with a code block, for example like this:
java -jar code.jar
When asking questions here - or indeed anywhere on the web where you can get technical help - try to ask yourself what clarifications you would need if you saw your question for the first time. Your first edit did not include your code, so ask yourself: would you be able to ascertain someone else's similar problem without code? Broadly here the answer is "no", and thus the moral of this story is: always include your code.
Also, do spend a moment to learn the code formatting tools. To use them, paste your block of code into the question, select it, and click the "code" button. It will apply a four-space Markdown indent, which you can now see in the question.
If you need to add clarifications to your post, it is OK to add them as comments, but do also edit the body of the question so that new readers can understand the question. It is well worth spending time making it as readable and clear as possible, so you can get the best possible help, and so that people do not take a look and decide that another question is a better use of their time.
Since you are using an IDE, do you get any warnings/errors in the editor, to help you identify potential problems in you code? If so, and you do not understand them, then paste them into your question, in order to clarify it.
Thanks for your advices... Finally made it working..
thank you once again
package practise;
public class code{
public static void main(String[] args){
int[] Array = {5,8,6,4};
int[] newArray = new int[Array.length];
int a, b, c, d, e, f =1;
for(int z : Array ){
d=0;
for(int i=0; i<Array.length; i++){
a = z; b = Array[i];
if( a >= b){
continue;}
else{
d++;}
}
c = Math.subtractExact(Array.length , d);
e = Math.subtractExact(c, f);
for(int j=0; j< Array.length; j++){
while( j == e){
newArray[j] = z;
break;
}
}
}
System.out.println("Here is your old Array :");
for(int k : Array){
System.out.println(k);
System.out.println("Here is your new Bubble Sort Array :");
for(int q : newArray){
System.out.println(q);
}
}
}
}

Methods not pulling through - Read Running Loop on Java Method, didn't fix my code

So I am a student. I am taking my first class in Java. I am sure my code is horrible, but please don't beat me up, I am really trying to learn. I have read quite a few method questions and adjusted my code according the the suggestions on this website. The closest post to my problem is Running Loop on Java Method. I adjusted my code according to the suggestions in this post, along with a few others. That said, it did not fix my problem. My methods are not pulling through properly.
Can anyone help? It will not pull any of the Boolean code into the main and I am not sure if the Boolean is pulling my methods correctly. Intro runs properly. Below is my code (edited down to include main and bool code only):
public static void main(String[] args)
{
intro(); // This works
while (repeat()) //This does not work
;
}//end Main
//None of this is being called
public static boolean repeat()
{
//Assign Variables
char calculate, calculateCS, repeat;
double inchCircle, inchSphere, radiusCS, volume, volumeSphere, area, areaCircle;
String shape;
//Initialze Variables
calculate = 1;
area = 1;
volume = 1;
inchCircle = 1;
inchSphere = 1;
shape = "";
//Ask if user wants to repeat
System.out.print("Do you want to calculate anouther round object (Y/N): ");
if (!takeInput().equalsIgnoreCase("y"))
{
System.out.println("Thank you for using the Round Object Calculator. Goodbye. ");
return false;
}
else
{
printCircleSphere(shape);
if (!printCircleSphere(shape).equalsIgnoreCase("c"))
{
printRadiusC(inchCircle);
printCircle(area);
}
else if (!printCircleSphere(shape).equalsIgnoreCase("s"))
printRadiusS(inchSphere);
printSphere(volume);
}
return true;
}//end repeat

Runtime error in UVA Online Judge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm doing problem 10003 "cutting sticks" of the UVa online judge, I'm pretty sure my code works and I think I' correctly exiting the problem. But still I get a runtime error, I read somewhere that is because I'm not exiting the application like I'm supposed to do it. I wish you guys can help me with this problem.
import java.io.*;
class MAIN {
static int len, c, min;
static int mat[][] = new int[52][52];
static int arr[] = new int [52];
static BufferedReader BufferReader = new BufferedReader(new InputStreamReader(System.in));
public static void llenaarr()throws IOException{
for(int i=0; i<c-1; i++) {
arr[i+1] = Integer.parseInt(BufferReader.readLine());
}
arr[0] = 0;
arr[c] = len;
}
public static void llenamat(){
for(int i=0; i<=c; i++) {
for(int j=0;j<=c;j++) {
mat[i][j] = Integer.MAX_VALUE;
}
}
for(int i=0; i<c; i++) {
mat[i][i] = 0;
mat[i][i+1] = 0;
}
mat[c][c] = 0;
for(int i=0; i<c-1; i++) {
mat[i][i+2] = arr[i+2] - arr[i];
}
}
public static void minimo(){
for(int k=3; k<=c; k++) {
for(int i=0; i<=c-k; i++) {
for(int j=i+1; j<=i+k-1; j++) {
min=mat[i][j] + mat[j][i+k] + arr[i+k] - arr[i];
if((min< mat[i][i+k])) {
mat[i][i+k] = min;
}
}
}
}
}
public static void main (String args[]) throws IOException {
while((len = Integer.parseInt(BufferReader.readLine())) > 0){
c = (Integer.parseInt(BufferReader.readLine()))+1;
llenaarr();
llenamat();
minimo();
System.out.println("The minimum cutting is "+mat[0][c]+".");
}
}
}
Your program is throwing some kind of runtime Exception during processing input. To verify this, you should encapsulate your code (the part that operates on the input and produces output) in a try-catch block.
The first thing to try to catch is the generic Exception. This will catch any type of runtime exception. Run it through the online judge again, and you should now see a Wrong Answer result (assuming something is not processing right, because it is throwing an exception after all).
Now comes the detective work. Go back to your source code and look at all the calls you make and use the API Docs to check all the possible exceptions they may throw. For example, if you call Integer.parseInt(inputString), it may be throwing a NumberFormatException. So above your catch (Exception e) block, start adding some more specific exceptions you think may be causing the problem.
Ideally (if you have the time and patience) you'll want to add these one at a time and resubmit to the online judge after each one. When the result moves from Wrong Answer back to Runtime Error, you'll know you've found the exception that is causing the problem. From here, hopefully this will help you narrow down what to focus on (to fix) in your source code solution.
Good luck.

Categories