how can i Use bets(if) for ReadKey in java - java

I'm a beginner java developer. I want to build a program that gets a number from the user, then say it's prime or not.
Java code:
import java.util.Scanner;
import static java.lang.System.out;
public class prime
{
public static boolean prime(int n)
{
for(int i = 2; i <n ; i++)
{
if(n % i == 0){
return false;
}
}
return true;
}
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
out.println("enter a number: ");
int x = input.nextInt();
if(prime(x)){
out.println(x + "is a prime number");
}else{
out.println(x + "isn't a prime number");
}
}
}
However, I want to declare a bool variable, then ask the user if they want to continue, the user then says yes or no. I have already written this code in C#:
C# code
class Program
{
static bool prime(int n)
{
for(int i = 2; i < n ; i++)
{
if(n % i == 0)
‌{
return false;
}
}
return true;
}
static void main(String[]args)
{
Bool permit = true;
While(permit)
{
Console.WriteLine(“enter a number”)
int x = int.Parse(Console.ReadLine());
if(prime(x))
{
Console.WriteLine(x + "is a prime number");
}
else
{
Console.WriteLine(x + " isn't a prime number");
}
Console.WriteLine(“do you want to continue”);
Permit = Console.ReadKey.Key() == ConsoleKey.Y?true:false;
}
}
}
How can I build it in Java?

You can't directly map your C# keyboard key press detection to Java.
AFAIK, checking which key is pressed can only be done via key listeners in Java AWT/Swing GUI programs [How to Write a Key Listener]. Your program, however, is a console program and Java doesn't have any mechanisms to detect which key was pressed in a console application. See this question for more info.
Now what you could do is read the String that a certain key press produced. Something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean permit = true;
while (permit) {
// your existing code
out.println("do you want to continue?");
permit = input.next("y|Y").equalsIgnoreCase("y");
}
}

I also corrected prime method.
import java.util.Scanner;
import static java.lang.Math.abs;
import static java.lang.System.out;
public class Prime {
public static boolean prime(int n) {
for (int i = 2; i < n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
try {
out.println("enter a number: ");
int x = Integer.parseInt(input.nextLine());
if (prime(x)) {
out.println(x + " is a prime number");
} else {
out.println(x + " isn't a prime number");
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
}
out.println("do you want to continue");
if (!input.nextLine().equals("Y")) break;
}
}
}

Just check if the key pressed is the y (yes) and if yes it continues in the cycle.
static void main(String[] args)
{
ConsoleKey response;
do
{
Console.WriteLine("enter a number");
int x = int.Parse(Console.ReadLine());
if (prime(x)) {
Console.WriteLine(x + " is a prime number");
} else {
Console.WriteLine(x + " isn't a prime number");
}
Console.Write("do you want to continue? [y/n] ");
response = Console.ReadKey(false).Key;
}
while (response == ConsoleKey.Y);
}

Related

how to make this code keep asking a number until finds a prime number?

I would like to have some ideas on how I can make this code to keep asking for a number until the program finds a prime number. Thank you so much :)
import java.util.Scanner;
class SieteDosEjerSeis {
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
Well, mainly what everyone said, you need a Loop that stops when the number typed in the scanner is a prime number.
In this case I would say is better to have another method to check if N is prime or not, for a cleaner code.
✓ Tested
import java.util.Scanner;
public class SieteDosEjerSeis {
public static void main(String[] args) {
boolean prime = false;
// loop until prime is true
while(prime == false){
Scanner s = new Scanner(System.in);
System.out.println("Enter a number:");
int n = s.nextInt();
s.close();
// is it prime?
prime = isPrime(n);
if (prime){System.out.println(n + " is a prime number.");}
else{System.out.println(n + " is not a prime number.");}
}
}
// method that returns true or false depending if N is prime or not
public static boolean isPrime(int num) {
if (num <= 1) {return false;}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {return false;}
}
return true;
}
}
You can extract the prime evaluation to a new method:
class SieteDosEjerSeis {
public static boolean isPrime(int num) {
for (int i = 2; i <= num/2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// ...
}
Then, change your IO code to be based on the result of this method:
class SieteDosEjerSeis {
// ...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (;;) {
System.out.println("Enter a number:");
int num = scan.nextInt();
if (!isPrime(num)) {
System.out.println("The number is not prime!");
continue;
}
break;
}
// This will only be reached if the number is prime
System.out.println("The number is prime.");
}
}
You can use do while loop for this.
class SieteDosEjerSeis {
public static void main(String args[]) {
int temp;
boolean isPrime=true;
do {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++) {
temp=num%i;
if(temp==0) {
isPrime=false;
break;
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
} while (!isPrime);
}
}

Are my loops preventing me from getting the expected output?

My goal is to determine, for a pair of integers, whether the second integer is a multiple of the first. My code is as follows:
import java.util.Scanner;
public class Multiples {
public static void main(String [] args) {
boolean run = true;
while(run) {
Scanner input = new Scanner(System.in);
System.out.print("Enter one number:");
int num1 = input.nextInt();
System.out.print("Enter a second number:");
int num2 = input.nextInt();
boolean result = isMultiple(num1, num2);
if(result) {
System.out.println(num2 + " is a multiple of " + num1);
} else {
System.out.println(num2 + " is not a multiple of " + num1);
}
System.out.print("Do you want to enter another pair(y/n)?");
run = YesOrNo(input.next());
}
}
public static boolean YesOrNo(String a) {
if(a.equals("y"))
return true;
else
return false;
}
public static boolean isMultiple (int x , int y) {
if(y % x == 0)
return true;
else
return false;
}
}
This is my output:
This is the expected output:
The expected output is confusing me.

Java classes and calling variables in other classes

I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}

Java - Continue a game

I made some command line games and at the end of the game I want to ask if the player wants to play again. You can see in the code how I made but it's not working and I don't know why.
Can anybody help me?
import java.util.Scanner;
//WIP
public class GuessingGame2 {
static Scanner userInput = new Scanner(System.in);
static int randNumber;
static int guessNumber;
static boolean gameStatus;
static void checkNum(int x) {
guessNumber++;
if(x == randNumber) {
gameStatus = true;
} else if(x < randNumber) {
System.out.println("Too small!");
} else {
System.out.println("Too big!");
}
}
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine() == "Y" || userInput.nextLine() == "y") {
guessGame();
} else if(userInput.nextLine() == "N" || userInput.nextLine() == "n") {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
static void guessGame() {
randNumber = (int) (Math.random() * 1000);
guessNumber = 0;
gameStatus = false;
System.out.println("Try to guess a number from 1 to 1000!");
while(gameStatus == false) {
System.out.print("Your guess: ");
if(userInput.hasNextInt()) {
checkNum(userInput.nextInt());
} else {
System.out.println("You need to choose a number!");
userInput.next();
}
}
System.out.println("You guessed the number in " + guessNumber + " tries.");
System.out.print("Do you want to play again? Y or N ");
checkAnsw();
}
public static void main(String[] args) {
guessGame();
}
}
Change your checkAnsw method to this:
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine().equalsIgnoreCase("y")) {
guessGame();
} else if(userInput.nextLine().equalsIgnoreCase("n")) {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
You cannot compare Strings with the = as they are objects. Use the .equals method to compare Strings.
Your code works fine, I have copied and pasted it in Eclipse and this is the output:
Try to guess a number from 1 to 1000!
Your guess: eeeee
You need to choose a number!
Your guess: 1
Too small!
Your guess: 2
Too small!
Your guess: 2
I don't understand which is your problem, try to explain better

palindrome numbers in java

Im new to java and I was wondering how i would print prime palindrome without using strings and only methods.
This is what I have so far. I want to print every prime palindrome number before 50. I did this with prime numbers only and it was working but when I added in palindrome, it did not work.
EDIT: i added in the int original = number like one of the answers says but my output is always 2,3,5,7,11 and nothing more.
EDIT2(1 more question): I changed the value up to 1000 and my output is 2 3 5 7 11 313 353 373 383 727 757 787 797 919 929. The output is correct but isn't 101, 131, 151, 181, 191 also prime palindrome numbers? Why are they not included in the output?
public class primePalindrome {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int num = input.nextInt();
System.out.println("The prime palindrome numbers are \n");
printPP(num);
}
public static void printPP(int numberOfPP) {
final int NUMBER_OF_PP_PER_LINE = 10;
int count = 0;
int number = 2;
while (number < numberOfPP) {
if(isPrime(number) && isPalindrome(number)) {
count++;
if (count % NUMBER_OF_PP_PER_LINE ==0) {
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
number++;
}
}
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
public static boolean isPalindrome(int number) {
int reverse = 0;
int n = number;
for (int i = 0; i <= number; i++) {
int remain = number%10;
number = number/10;
reverse = reverse*10+remain;
}
if (reverse == n) {
return true;
}
}
return false;
}
}
There's only one 2-digit prime palindrome: 11. Every other 2-digit number is divisible by 11. Your output is thus correct.
Your isPalindrome is quite close:
1) Move the equality check outside the loop
2) Use while-loop. Using "for" results in omitting palindrome patterns 1X1, 2XX2 etc.
3) Dont't forget to preserve the argument:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
while (number > 0) {
int digit = number%10;
number = number/10;
reverse = reverse*10+remain;
}
return reverse == original;
}
You were close. At the end you compare number to reverse. Unfortunately, number has been modified. You need to compare number's original value to reverse. Here's my modified version:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
for (int i = 0; i <= number; i++) {
int remain = number % 10;
number = number / 10;
reverse = reverse * 10 + remain;
}
return reverse == original;
}
/* Palindrome Program In JAVA
Credit: Code Nirvana (www.codenirvana.in)
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}
}
Since most of the answers above doesn't work for both positive and negative numbers, following is one which works for negative numbers as well.
private static boolean isPalindrome(int n) {
int orignal = n, reversed = 0;
while (n != 0) {
reversed = (reversed * 10) + (n % 10);
n /= 10;
}
return reversed == orignal;
}
What if the given input is a huge number or a string?
I believe the below code should work for any input.
private boolean isPalindrome(String s) {
int lo = 0, hi = s.length()-1;
while(lo < hi) {
if(s.charAt(lo) == s.charAt(hi)) {
lo++; hi--;
} else {
return false;
}
}
return true;
}
import java.util.Scanner;
/*if given number is same with reverse number
then this number is called as Palindrome number. */
public class PalindromeNumber {
public static void main(String args[])
{
int input,store,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
store=input;
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
if (output == store)
{
System.out.println("This is a palindrome number.");
}
else
{
System.out.println("This is not a palindrome number.");
}
in.close();
}
}
import java.util.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class cpalindrome
{
public static void main(String ar[])throws Exception
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number\n");
int n=sc.nextInt();
int s=0,r;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n/=10;
}
if(n==s)
System.out.println("palindrome\n");
else
System.out.println("not a palindrome");
}
}
import java.util.*;
public class PalPrime
{
public boolean prime(int n)
{
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
public boolean palindrome(int n)
{
int rev=0,temp=n;
while(temp!=0)
{
rev=rev*10+(temp%10);
temp=temp/10;
}
if(rev==n)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter number to be checked");
int num=ob.nextInt();
PalPrime obj=new PalPrime();
if(obj.prime(num)==true && obj.palindrome(num)==true)
System.out.println(num+" is a Prime Palindrome i.e. a PalPrime Number");
else
System.out.println(num+" is not a PalPrime Number");
}
}
TRY THIS!
This is easy to Understand
public class StringDemo {
public static void main(String args[]) {
if(palindrome("1211")){
System.out.println("Yes IT IS palindrome");
}
if(palindrome("121")){
System.out.println("Yes IT IS palindrome");
}
}
public static boolean palindrome(Object o){
String s=(String)o;
boolean result=true;
int temp=s.length()-1;
for(int c=0;c<temp;c++){
if(s.charAt(c)==s.charAt(temp)){
temp--;
//System.out.println("Pallidrom start "+ s.charAt(c));
//System.out.println("Pallidrom end "+ s.charAt(temp));
}else{
System.out.println("NOT palindrome");
return false;
}
}
return result;
}
}
Result is

Categories