Palindromic numbers in Java - java

I write program to solve several problems with numbers. My program should:
Welcome users;
Display the instructions;
Ask for a request;
Terminate the program if a user enters zero;
List item
If a number is not natural, print an error message;
Print the properties of the natural number;
Continue execution from step 3, after the request has been processed.
I got an error:
The program should continue to work till the user enter 0.
Here is my code:
package numbers;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Amazing Numbers!\n" +
"\n" +
"Supported requests:\n" +
"- enter a natural number to know its properties;\n" +
"- enter 0 to exit.\n" +
"\n" +
"Enter a request:");
int number = scanner.nextInt();
if (number >= 0) {
System.out.println("Properties of " + number);
System.out.println("\t even: " + (number % 2 == 0));
System.out.println("\t odd: " + (number % 2 != 0));
System.out.println("\t buzz: " + checkBuzzNumber(number));
System.out.println("\t duck: " + checkDuckNumber(number));
System.out.println("\t palindromic: " + checkPalindromicNumber(number));
} else {
System.out.println("The first parameter should be a natural number or zero.");
}
}
public static boolean checkBuzzNumber(int number) {
return number % 7 == 0 || String.valueOf(number).endsWith("7");
}
public static boolean checkDuckNumber(int number) {
String num = String.valueOf(number);
boolean flag = false;
if (num.startsWith("0")) {
return false;
} else {
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) == '0') {
flag = true;
break;
}
}
return flag;
}
}
public static boolean checkPalindromicNumber(int number) {
int rem, rev = 0, temp;
temp = number;
while (number != 0) {
rem = number % 10;
rev = rev * 10 + rem;
number = number / 10;
}
if (temp == rev)
return true;
else
return false;
}
}

You are just a loop away from getting the desired output, below is the code with comments to understand properly. Also, I have commented the code which you wrote but I removed from there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// System.out.println("Welcome to Amazing Numbers!\n" +
// "\n" +
// "Supported requests:\n" +
// "- enter a natural number to know its properties;\n" +
// "- enter 0 to exit.\n" +
// "\n" +
// "Enter a request:");
// int number = scanner.nextInt();
//-------------------------------------------------------------
while (true)// added an infinite while loop, in order to display and take input continuously
{
System.out.println("Welcome to Amazing Numbers!\n" +
"\n" +
"Supported requests:\n" +
"- enter a natural number to know its properties;\n" +
"- enter 0 to exit.\n" +
"\n" +
"Enter a request:");
int number = scanner.nextInt();
if (number == 0)// checks for the number to be zero or not.
{
break; // jump statement, breaks out of the loop.
}
if (number > 0) {// if entered number is greater than zero,
System.out.println("Properties of " + number);
System.out.println("\t even: " + (number % 2 == 0));
System.out.println("\t odd: " + (number % 2 != 0));
System.out.println("\t buzz: " + checkBuzzNumber(number));
System.out.println("\t duck: " + checkDuckNumber(number));
System.out.println("\t palindromic: " + checkPalindromicNumber(number));
System.out.println();// for a new line
}
else // if number is less than zero,
{
System.out.println("The first parameter should be a natural number or zero.\n");
}
}
scanner.close();//good practice to close the scanner.
//____________________________________________________________
// if (number >= 0) {
// System.out.println("Properties of " + number);
// System.out.println("\t even: " + (number % 2 == 0));
// System.out.println("\t odd: " + (number % 2 != 0));
// System.out.println("\t buzz: " + checkBuzzNumber(number));
// System.out.println("\t duck: " + checkDuckNumber(number));
// System.out.println("\t palindromic: " + checkPalindromicNumber(number));
// } else {
// System.out.println("The first parameter should be a natural number or zero.");
// }
}
public static boolean checkBuzzNumber(int number) {
return number % 7 == 0 || String.valueOf(number).endsWith("7");
}
public static boolean checkDuckNumber(int number) {
String num = String.valueOf(number);
boolean flag = false;
if (num.startsWith("0")) {
return false;
} else {
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) == '0') {
flag = true;
break;
}
}
return flag;
}
}
public static boolean checkPalindromicNumber(int number) {
int rem, rev = 0, temp;
temp = number;
while (number != 0) {
rem = number % 10;
rev = rev * 10 + rem;
number = number / 10;
}
if (temp == rev)
return true;
else
return false;
}
}

Related

How the consecutive numbers can be replaced with the range of number and random number should be as it is?

If there are numbers in which some are in sequence and some are random number, then how the consecutive numbers can be replaced with the range of number and random number should be as it is?
for eg: 1,2,3,4,5,6, 458,243
output: 1-6,458,243
I have just solved this problem..Its super simple just some if-else condition, however, I don't think about efficient way, so please follow the solution and try to efficient it.
public static void main(String[] args) {
int [] numberList = {1,2,3,4,5,6,458,243};
int initialSequence = -1;
int endSequence = -5;
for (int num = 0; num<numberList.length;num++) {
if(num<numberList.length-1) {
if(initialSequence == -1 && numberList[num] == numberList[num+1]-1) {
initialSequence = endSequence = numberList[num];
}else if(initialSequence == -1 && numberList[num] != numberList[num+1]-1){
System.out.print(numberList[num] + " ");
}else if(initialSequence != -1 && numberList[num] == numberList[num+1]-1) {
endSequence = numberList[num];
}
else {
System.out.print(initialSequence + "-" + (endSequence+1) + " ");
initialSequence = -1;
endSequence = -5;
}
}else {
if(initialSequence == -1) System.out.print(numberList[num] + " ");
else {
System.out.print(initialSequence + "-" + (endSequence+1) + " ");
}
}
}
}

I'm stuck with while loop on my random number guessing game

Want it to loop through everything until the user puts in the right number. When the user puts in wrong number it should say "type in a different number". When the user puts in the right number it should say "congrats you won". But until then it will loop and say "type in a different number" and after 5 tries I want it to say "you failed this mission! do you want to try again?"
If they guess it on 1 try they will be giving 500 dollar and second try 400 dollar and so on until 5 tries.
import javax.swing.*;
import java.util.Random;
public class Projekt_1 {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "WELCOME TO GUESS GAME!" + "\nYou gonna guess a number between 1 and 20 " + "\nYou have 5 tries to guess the number! " + "\nYou gonna get more money on less tries, highest win are 500 dollar on one try! " + "\nHOPE YOU LIKE IT :)");
Random talet = new Random();
int secretnumber = talet.nextInt(20) + 1;
int tries = 0;
int money = 600;
String number;
int guess;
boolean win = false;
while (win == false) {
number = JOptionPane.showInputDialog("Guess a number between 1 and 20");
guess = Integer.parseInt(number);
tries++;
if (guess == secretnumber) {
win = true;
} else if (guess > secretnumber) {
JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!");
guess = Integer.parseInt(number);
} else if (guess < secretnumber) {
JOptionPane.showInputDialog("Your number is to high :(" + "\nType ina a lower number!");
guess= Integer.parseInt(number);
}
}
JOptionPane.showMessageDialog(null, "Congrats you won!" + "\nYour number was " + secretnumber + "\nit took you " + tries + "tries");
}
}
Adding an additional condition in while loop will work. If försök is the number of tries which can have maxium value of 5 (in your case) then condition should be :
while (win == false && försök<5) //if försök starts from 0
{
//code
if(win==true)
break;
försök++;
}
To display the message and score you can just check the value of försök after while loop:
if(försök==5)
{
// display this message: "you failed this mission! do you want to try again?"
score=0;
}
else
{
//display: "congrats you won"
score=(5-försök)*100;
}
Basically your code should be like this:
import javax.swing.*;
import java.util.Random;
class Projekt_1
{
public static void main(String[] args) {
final int maxTries = 5;
JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");
final Random rnd = new Random();
final int hemligtnummer = rnd.nextInt(20) + 1;
int tryCounter = 0;
final int pengar = 500;
String nummer;
int guess = -1;
while (guess != hemligtnummer && tryCounter < maxTries) {
if(tryCounter==0)
nummer = JOptionPane.showInputDialog("...a number 1 and 20");
else
nummer = JOptionPane.showInputDialog("Enter no...");
guess = Integer.parseInt(nummer);
if (guess == hemligtnummer) {
break;
} else if (guess > hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " was too big try a smaller one");
} else if (guess < hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " too small try a bigger one");
}
tryCounter++;
}
if(tryCounter==5){
JOptionPane.showMessageDialog(null,"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
}
else
{
JOptionPane.showMessageDialog(null,"congrats you won"+"Your price is :" + (pengar - tryCounter * 100) + " Krones" );
}
}
}
you can have a control break while loop. which will be broken when the number of attempts become more then 5 OR when the correct number is inputted.See the below for reference
Scanner s = new Scanner(System.in);
int numOfTries = 0;
int input;
int correctNumn = 15;
while (true) {
input = s.nextInt();
if (input != correctNumn && numOfTries <= 5) {
numOfTries++;
if (numOfTries == 5) {
System.out.println("Game Over");
break;
}
continue;
} else if (input == correctNumn) {
System.out.println("corect ans");
break;
}
}
It is really hard to help you if you post all in your native language... but here is my answer...
the issue with your code was in the hole logi, you never use the variable tries(försök) and If the user guess a wrong number then you read the try again but instead you should start the logic of the while again....
anyways....
Example:
public static void main(String[] args) {
final int maxTries = 5;
JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");
final Random rnd = new Random();
final int hemligtnummer = rnd.nextInt(20) + 1;
int tryCounter = 0;
final int pengar = 600;
String nummer;
int guess = -1;
while (guess != hemligtnummer && tryCounter < maxTries) {
nummer = JOptionPane.showInputDialog("...a number 1 and 20");
guess = Integer.parseInt(nummer);
tryCounter++;
if (guess == hemligtnummer) {
break;
} else if (guess > hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + tryCounter + " was too big try a smaller one");
} else if (guess < hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + tryCounter + "too small try a bigger one");
}
}
JOptionPane.showMessageDialog(null,
"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
}

I have to create a High Low game. I don't understand why it won't work

public static void main(String[] args) {
int money = 100, roll1, roll2;
int userBet;
char c;
int lostwin;
Scanner in = new Scanner(System.in);
do {
if (money == 0 || money < 0)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (true);
}
private static int getBet(Scanner inScanner, int moneyPot) {
System.out.println("Enter an amount to bet (0 to quit): ");
int result = inScanner.nextInt();
if (result > moneyPot) {
do {
System.out.println("Enter an amount to bet (0 to quit): ");
result = inScanner.nextInt();
} while (result > moneyPot);
}
return result;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}
private static int getRoll() {
return (int) (Math.random() * 6) + 1;
}
private static int determineWinnings(char highLow, int bet, int roll) {
int result = 0;
if (highLow == 'H') {
if (roll < 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'L') {
if (roll > 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'S') {
if (roll == 7) {
result = 4 * bet;
} else {
result = -1 * bet;
}
}
return result;
}
I need the program to say "Goodbye!" when the user enters the number 0, but I can't figure out where to put it or how to get it to work. The other issue I need help with is if the user enters a number higher than 100 or less than 1, the program needs to say "Your bet MUST be between 0 and 100 dollars". I don't know where to put them or how to get them to work.
You can modify your getBet function like this to achieve what you want.
private static int getBet(Scanner inScanner, int moneyPot) {
int result;
System.out.println("Enter an amount to bet (1-100) (0 to quit): ");
do {
result = inScanner.nextInt();
if (result == 0) {
System.out.println("Good Bye");
return result;
} else if (result < 0 && result > 100) {
System.out.println("Please enter an amount between (1-100) (0 to quit)");
} else if (result > moneyPot) {
System.out.println("Please enter an amount less than your moneyPot between (1-100) (0 to quit)");
} else {
return result;
}
} while (true);
}
public static void main(String[] args) {
int money = 100;
int roll1;
int roll2;
int userBet;
int lostwin;
char c;
Scanner in = new Scanner(System.in);
do {
if (money < 1)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (money > 0);
System.out.println("Goodbye!");
}
private static int getBet(Scanner inScanner, int moneyPot) {
int bet;
do {
System.out.println("Enter an amount to bet (0 to quit): ");
bet = inScanner.nextInt();
} while (bet > moneyPot && bet != 0);
return bet;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}

Encountering Error with Pig Code

My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.

Ask users if user wishes to re-run the program

I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.

Categories