Java: RuntimeException when run on spoj.com - java

Following is the question for prime number generator problem (from spoj.com):
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input :
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output :
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example :
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Following is my code for the same:
package competitivecoding;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Scanner st = new Scanner(System.in);
int t = sc.nextInt(); // inputs the "no." of lines that users want to enter
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[2];
for(int i=0; i<t; i++){
line[i] =st.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
System.out.println();
}
}
}
Error: The code when submitted, produces RuntimeException on spoj.com, although it works completely fine on my system.

package abc;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[10];
for(int i=0; i<t; i++){
line[i] =sc.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");}
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
}
}
//try this

Always handle the exception that can be raised (ideally, any exceptional behaviour that you can recover from, accoding to the Oracle documentation for Exception) and never consider user input as safe:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = 2;
try {
/* for each line */
for (int i = 0; i < t; i++) {
/* read the line */
String line = br.readLine();
/* split the line */
String[] numbers = line.split(" ");
if (numbers.length != 2)
throw new ArrayIndexOutOfBoundsException();
/* parse values */
int min = Integer.parseInt(numbers[0]);
int max = Integer.parseInt(numbers[1]);
/* do your check */
__find_prime_numbers__
}
}
catch (NumberFormatException ex) {
/* notice the user -> input format isn't correct, for example: "1 m" */
}
catch (ArrayIndexOutOfBoundsException ex) {
/* notice the user -> input format isn't correct, for example: "1 " or "1 2 3" */
}

It works for me. Print the error so we have more info.
You can also do Scanner.nextInt().
Things like multiple spaces , tabs can mess stuff

Are you using sc.nextInt() before the first sc.nextLine()? because if that's the case, you could have a '\n' character in the buffer after using it. So when you use nextLine() for the first time, you actually get the '\n' character instead of the next line. And when you try to parse to integer it fails.
See here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
If this is the case, the solution is simple. Just fire a call sc.nextLine() that does nothing except to 'eat' that character from the buffer.

Related

Possible Workaround for Optimal solution for split function in java while reading multiple lines?

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two or more numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Print Each number in Separate line which can be used further for summation
Input
2
50 100
100 50 105
Output
50
100
100
50
105
Now this is the code that i've written that is Giving me Output
import java.util.Scanner;
import java.util.StringTokenizer;
public class Generation {
public static void main(String[] str) {
Scanner keyboard = new Scanner(System.in);
int inputSize;
do {
System.out.println("Enter the value of T Size");
inputSize = keyboard.nextInt();
keyboard.nextLine();
if (inputSize < 2 || inputSize > 10) {
System.out.println("Not a Valid Input Size");
}
} while (inputSize < 2 || inputSize > 10);
String[] inputValue = new String[inputSize];
int tokenCount = 0;
for (int i = 0; i < inputSize; i++) {
System.out.println("Enter the inputs");
inputValue[i] = keyboard.nextLine();
StringTokenizer strToken = new StringTokenizer(inputValue[i], " ");
tokenCount += strToken.countTokens();
}
keyboard.close();
//suppose this is 2nd part
int[] splitedString = new int[tokenCount];
int tempTokenCount = 0;
for (int i = 0; i < inputSize; i++) {
String[] tempSplitArray = inputValue[i].split(" ");
for (int j = 0; j < tempSplitArray.length; j++) {
splitedString[tempTokenCount] = Integer
.parseInt(tempSplitArray[j]);
tempTokenCount++;
}
}
/*for (String s : inputValue) {
System.out.println(s);
}*/
for (Integer s : splitedString) {
System.out.println(s);
}
}
}
Now my question is how can i optimize the 2nd part where i have to use two for loop which result in O(npower2) time complexity. What is the workaround for such situations ?
You are concerned with performance, and I see you have some knowledge of the issues (taking about power time complexity) but I think you don't really fully understand what this means.
Just because your program has nested loops, doesn't mean it is (much) less efficient than one with a single loop. The outer loop iterates over each line and the inner loop iterates over the tokens (which vary in number) so the total number of iterations is the total number of tokens and has nothing to do with any power law.
The main problems with performance is that you simply have too much code to do a very simple thing and you are using temporary arrays, scanners, parsers which will all add to the overhead of it. You can read a file containing its with the following code:
import java.util.Scanner;
public class Scan {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int i;
while (keyboard.hasNext()) {
try {
i = keyboard.nextInt();
System.out.println(i);
} catch(Exception e) {
// Whatever
System.err.println(e.getMessage());
System.exit(1);
}
}
}
}
This will do most of what your class does and in addition catches exceptions. The only thing it doesn't do is read the initial count of lines. Actually, counting lines is hard in the scanner as it doesn't really support it, but maybe you can do without that or have another solution.

How do I get my value to print every time the loop increments in Java (For Loop)

I need to create a code that prints a pyramid like structure, given the user integer input which will be printed last. (I have attached an image of a final product below). I am new to programming, have been enjoying it, but am stuck in this problem.
My code can currently produce the user input 4 times. So I feel like I am close, just a little bit of tweaking will get the job done
I need my code to print out every single time that the loop increments instead of just displaying the user input a certain amount of times. I converted the integer to a string so that I can show the value x amount of times, but I feel that this is what is throwing me off. If I can somehow get the string to display the values at every incrementation then I will be golden. PLEASE HELP! Below is my code
import java.util.Scanner; //import scanner
public class NumberStack { // class
static Scanner myScanner; //declare scanner
public static void main(String[] args){ //add main method
myScanner= new Scanner (System.in); //scanner input declaration
int input= 0;
while (true) {
System.out.print("Enter an integer between 0 and 9 inclusive: ");
if (!myScanner.hasNextInt()) {
System.out.println("You have not entered an integer");
}
input= myScanner.nextInt();
if ( (input>=0) && (input<=9) ) {
String smln= Integer.toString(input);
String out="";
for (int p=0; p<input; p++) {
for (int j=0; j<input; j++) {
for (int i=0; i<((input*2)-1);i++) {
out += smln;
}
System.out.println(""+out);
out="";
smln= Integer.toString(input);
}
}
} //end of if statement
else {
System.out.println("You have not entered an integer within range");
}
} //end of while loop
} //end of main method
} //end of class
when you are facing problems like this one, you should try to look for a pattern...check this out
int input = 4;
for(int i = 1; i <= input; i++)
{
int times = i;
int length = 2 * i - 1;
String str = "";
for(int j = 0; j < length; j++)
{
str += i;
}
for(int k = 0; k < times; k++)
{
System.out.println(str);
}
}
Since your method is currently printing the data fro a particular number properly eg for input 4 it is printing
4444
4444
4444
4444
I would suggest that extract ur code for display into a separate function. And call that function using the number from a loop.
for(int i=1; i<=num;i++)
function_f1(i);
This should do the trick for you and since you are starting off with coding , it will also give you ideas on using methods.

Guessing random number game error

Below Is My Code , I Cant figure out , how can i make the user to have only 4 tries then its say you lost , try again ? why cant this work ? i am doing something wrong in the for loop ? or should i use another loop
public class JavaApplication11 {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int random = (int )(Math.random() * 10 + 1);
// System.out.println("Random Number Is:"+random);
double userinput = 0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("-------------------------------------------------");
System.out.println("Welcome To The Guessing Game!");
System.out.println("-------------------------------------------------");
System.out.println("Lets Start,Guess The Number:");
System.out.println("-------------------------------------------------");
userinput=Integer.parseInt(br.readLine());
for(int i=random;i<=4;i++)
{
if(userinput==random)
{
System.out.println("-----------------------------------------");
System.out.println("You Won!");
System.out.println("-----------------------------------------");
}
else {
System.out.println("--------------------------------------------");
System.out.println("Wrong Guess,Try Again! Good Luck^_^");
System.out.println("--------------------------------------------");
}
System.out.println("Created By XYZ!");
}
}
}
for(int i=random;i<=4;i++) looks suspect: there's no reason to initialise i to the random number picked by the computer.
I think you meant for (int i = 1; i <= 4; i++) instead.
You need to put
userinput=Integer.parseInt(br.readLine());
into your for loop if not successful.
else {
userinput=Integer.parseInt(br.readLine());
....
}
also the foor loop should be
for(int i=0; i < 4; i++)
There several mistakes in your program:
1. You can not guarantee user inputs a legal number. So, U should judge if br.readLine() is a integer number. The code is:
str = br.readLine();
while(!str.matches("[0-9]+")) {
System.out.println("Input Format Error!! Please Re. input:");
str = br.readLine();
}
userinput = Integer.parseInt(str);
2. The for loop should be coded as below if you wanna tried only 4 times:
for(i = 1 ; i <= 4 ; i++)
3. In the for loop, you should have interface for Re. input when the answer is wrong.
str = br.readLine();
while(!str.matches("[0-9]+")) {
System.out.println("Input Format Error!! Please Re. input:");
str = br.readLine();
}
userinput = Integer.parseInt(str);
4. if you wanna loop this process for many times, you should put all codes in a while(true){...} loop.
Here are my suggestion:
1.Read user input in each try.(BufferedReader with in the loop)
2.If user win break the loop.
3.Loop should be run 4 times only,
for (int i = 1; i <= 4; i++)
you have to look to "random" variable !!
you initialised it like :
int random = (int )(Math.random() * 10 + 1);
sometimes it is >4 , that's the problem caused on the For iterator

writes several line to standard out put in reverse order

I want to write a program in java that takes all the lines input to standard input and writes them to standard output in reverse order.
this is may code but it has an error and I can't understand where is the problem
(In this program at first I ask for the number of lines and then save it in 'n'.)
any help?
thanks in advance
package getLine;
import java.util.Scanner;
public class S {
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n= s.nextInt();
String [] str;
str= new String[n];
for(int i=0;i<n;i++)
str[i]=s.nextLine();
for(int i=n;i>=0;i--)
System.out.println(str[i]);
}
}
Why don't you use a Stack<String> to buffer the lines? Then simply pop every line and output it.
Following is the code with output:
import java.util.Scanner;
public class S {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n = s.nextInt();
System.out.println("I want to enter " + n + " lines ");
n = n + 1;
String[] str;
str = new String[n];
int count = 0;
for (int i = 0; i < n; i++) {
str[i] = s.nextLine();
System.out.println(str[i]);
count++;
}
if (count == n) {
System.out.println("Reversed output");
for (int i = n - 1; i >= 0; i--) {
System.out.println(str[i]);
}
}
}
Output:
how many lines do you want to enter
2
I want to enter 2 lines
1
1
2
2
Reversed output
2
1
for(int i=n-1;i>=0;i--)
System.out.println(str[i]);
Do you get ArrayIndexOutOfBoundsException? The error lies here:
for(int i=n;i>=0;i--)
System.out.println(str[i]);
In the first step of that loop you attempt to print str[n], which doesn't exist.
Your array consists of n elements numbered from 0 to n-1.
The proper code is:
for(int i = n - 1; i >= 0; i--)
System.out.println(str[i]);
You need to start from n-1 because the maximum index accessible in an array is array.length-1.
for(int i=n-1;i>=0;i--){
Also you need to make this change:-
int n= Integer.parseInt(s.nextLine());
s.nextInt() reads the next integer all right, but the enter you hit after that, is consumed as the first element of your array. To avoid that, you can do as I mentioned above.
You don't have to do much to handle this, just replace your line in a code by the following code-
int n = s.nextInt()+1;

Reading user input

I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.
for example
enter up to 5 numbers : 3 4 5
I'm going to add them in the integer sum and then later divide them by counter
to get the average of these numbers.
However, my loop does not seem to end. What's wrong with my code?
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt());{
counter++;
sum += scan.nextInt();
}
System.out.println(counter);
System.out.println(sum);
You put a ; between while and {, so it loops. Remove it.
Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.
What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:
String input = scan.nextLine();
for(String part : input.split(" "))
sum += Integer.parseInt(part);
Serge Seredenko's answer is also correct, however, but that's another problem.
Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt()){
counter++;
sum += scan.nextInt();
if(counter >=5)
break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();
First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete.
Second, when you use your code, you need CTRL + Z to end up your input. By adding
if(counter >=5)
break;
your input will end up when you input 5 numbers.
If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.
I would suggest you to read line then split by space and iterate over string array. Check out code snippet.
package com.gaurangjadia.code.java;
import java.util.Scanner;
public class SO19204901 {
public static void main(String[] args) {
int counter = 0,
sum = 0;
System.out.println("enter up to 5 numbers");
Scanner scan = new Scanner(System.in);
String strInput = scan.nextLine();
String[] arrayNumbers = strInput.split(" ");
for (int i = 0; i < arrayNumbers.length; i++) {
int n;
try {
n = Integer.parseInt(arrayNumbers[i]);
}
catch (NumberFormatException e) {
n = 0;
}
sum = sum + n;
counter++;
}
System.out.println(sum);
}
}
DataInputStream in = new DataInputStream(System.in);
String[]label = {"quiz #","Total","Average"};
int counter = 0;
int theSum = 0;
System.out.print("Enter up to 5 number : ");
String[]tempNum = in.readLine().trim().split("\\s+");
System.out.println();
while (counter <= tempNum.length)
{
if ( counter == tempNum.length)
{
System.out.printf("%10s %12s\n",label[1],label[2]);
counter = 0;
break;
} else {
System.out.printf("%10s",label[0] + (counter+1) );
}
counter++;
}
while(counter <= tempNum.length)
{
if ( counter == tempNum.length)
{System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
} else
{System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
theSum += Integer.valueOf(tempNum[counter]);
}
counter++;
}

Categories

Resources