Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String to Integer Conversion getting from Console  RSS feed

 
Sheetal Kaul
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm not getting how to convert my value which is i'm getting from the console.

My Program is ::


import java.util.*;
import java.io.*;
import java.*;
public class Prime{

public static void main(String[] args) throws IOException
{
InputStreamReader stdin = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(stdin);

String message = " ";
System.out.println("Enter Prime Number :: ");
message = console.readLine();

System.out.println("Console message : " + message);
}
}

I want to get the value of message in Integer Format & want to chec whether the value entered is prime or not.

plz can any1 help me.


Thanks
Sheetal
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The integer bit is easy.

int i = Integer.parseInt(input)

That can throw an exception, so you have the choice of catching the exception or letting it bubble up to a calling routine and perhaps kill the program.

Telling whether it is prime is harder. Have you been given any hints on how to go about it?
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start with the square root of your given number.
If division of the int by each and every number from the square root of "int" to 2 always leaves a remainder, then you have a prime number.
 
Sheetal Kaul
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey i got the correct One. Thanxs for all ur Help.

Thanxs
Sheetal
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Small but important performance improvement for the prime calculation: try to divide only by other primes, not by every odd number smaller than the square root.

May not sound like it does much but as you get higher it will really speed you up (for the simple reason that the number of primes increases more slowly than the number of odd integers).

Of course this means keeping a list of primes in memory from earlier calculations, something that may be a problem on memory starved devices or when you go to extremely large numbers.
In the first case you may want to ask yourself if you really want to calculate primes at all (as those are often also CPU starved), in the second case there's more complex but faster algorithms to use (see a specialist book or research paper).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!