This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 5 years ago.
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome.
package com.practise.examples;
import java.util.Scanner;
public class Practise
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
int revNum=0;
while(num!=0)
{
revNum=revNum *10;
revNum= revNum+ num%10;
num=num/10;
}
System.out.println("the reverse of the number is: " +revNum);
if(revNum==num)
{
System.out.println("the number is a palindrome" );
}
else
{
System.out.println("the number entered is not a palindrome");
}
}
}
Easier way:
String num=Integer.toString(s.nextInt());
String revNum = new StringBuffer(num).reverse().toString();
System.out.println("the reverse of the number is: " +revNum);
if(revNum.equals(num))
System.out.println("the number is a palindrome" );
else
System.out.println("the number entered is not a palindrome");
If you're insisting on your method:
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
int original = num;
int revNum=0;
while(num!=0)
{
revNum=revNum *10;
revNum= revNum+ num%10;
num=num/10;
}
System.out.println("the reverse of the number is: " +revNum);
if(revNum==original)
{
System.out.println("the number is a palindrome" );
}
else
{
System.out.println("the number entered is not a palindrome");
}
}
Try something like this:
public static int reverse(int num)
{
try
{
return Integer.parseInt(new StringBuilder(String.valueOf(num)).reverse().toString());
}
catch (Exception ex)
{
// Should not happen...
}
}
You have modified num for getting the reverse, and then using the same num for comparison. Use temporary variables.
your idea seems to only work in VERY specific instances, and the code itself... well, ill just give you a different idea.
create a stack and a queue.
take the original input, and add each consecutive item to each the stack and the queue.
once the queue and stack are full...
iterate until length=0
if stack.pop != queue.dequeue
palindrome=false
you can cast your number to a string and check doe's its palindrome?
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
if (isPalindrome(num+"")){
System.out.println("the number is a palindrome" );
}else{
System.out.println("the number entered is not a palindrome");
}
}
public static boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
So the code is supposed to continually give fibonacci values for any given number until you enter "q", but for some reason instead of stopping, I get an error, anyone know why? I know that if you try to parse a string, it will cause the error but I have "if(input != "q")" to stop that so why is it still happening?
Tester class:
import java.util.Scanner;
public class FibonacciTester
{
public static void main(String[] args)
{
String input = "1";
System.out.println("Input a positive integer that you want to find the fibonacci number for");
System.out.println("Type 'q' to quit");
Scanner in = new Scanner(System.in);
while (input != "q"){
System.out.print("Type in the positive integer");
input = in.next();
if(input != "q"){
int number = Integer.parseInt(input);
FibonacciV fibonacci = new FibonacciV(number);
number = FibonacciV.fibonacci(number);
System.out.println("The Fibonacci number: " + number);
}
}
}
}
Class
public class FibonacciV
{
FibonacciV(int x)
{
}
public static int fibonacci(int x)
{
if (x == 0) //Base case
{
return 0;
}
else if (x == 1) //Second base case
{
return 1;
}
else
{
return fibonacci(x-1)+ fibonacci(x-2); // recursive call
}
}
}
Change input != "q" to !input.equals("q").
Read more about how to compare strings in java.
You are getting NumberFormatException because it's running Integer.parseInt(input) when the input is "q", which is not a number. And the code was able to reach this statement because your string comparison is incorrect.
Using Java to compile a code that takes in any input, from strings to doubles, floats, integers, etc., but can only process based on integers. If it receives a double, float, or a string, it will just produce a message prompting the user to try again. I'm not sure exactly how to get this rolling, so here's my current code.
import java.util.Scanner;
public class Sand
{
public static void main(String[] args)
{
int firstInt, secondInt, thirdInt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hi. I'm going to be asking you for three integers in just a moment.");
System.out.println("An integer is defined as a WHOLE number that's not a fraction or decimal.");
System.out.println("I swear to you, I will go off if you put in a non-whole number...");
System.out.println("Okay go ahead and type in the first of the three integers:");
if (keyboard.hasNextInt())
{
firstInt = keyboard.nextInt();
System.out.println("Red.");
System.out.println("So the first integer is " + firstInt);
System.out.println("Okay go ahead and type in the second of the three integers: ");
if (keyboard.hasNextInt())
{
secondInt = keyboard.nextInt();
System.out.println("Green.");
System.out.println("So the first and second integers are " + firstInt + " and " + secondInt);
}
else
{
System.out.println("Orange.");
System.out.println("Please try again.");
}
}
else
{
System.out.println("Blue.");
System.out.println("Please try again.");
}
}
}
I have orange and blue representing times in which there are some input errors, but it's not complete. I'm not sure how to approach this, be it a while loop or a for loop or a try/catch. I'm new when it comes to learning Java so some #notes would be helpful along the way. The code is to designed to read three numbers that are integers from the user in a string. That's straightforward, but analyzing the input is where I'm struggling.
This is not meant to answer your question totally but to point you in the right direction. There should be enough here to help you figure out what else is needed for your program.
import java.util.Scanner;
public class Sandbox {
// arguments are passed using the text field below this editor
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = 0;
System.out.println("enter an integer");
while (true) { //keep prompting the user until they comply
try {
num = Integer.parseInt(keyboard.nextLine());
keyboard.close();
break;
} catch (NumberFormatException e) {
System.out.println("You must enter an integer");
}
}
System.out.println("num: " + num);
}
}
I, personally, would use an array or arrayList (based on your needs) to store the int values and then use a while loop to check and accept the numbers. while (array.length < 3) do {int checking}. This way the script will not run if there are already 3 values in the array and will run until you get 3 values.
this should do the job..
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
System.out.print("input integer #"+(i+1)+": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #"+(i+1)+": " + intArray[i]);
} else
{
System.out.println("not an integer");
break;
}
}
keyboard.close();
}
}
or maybe another solution that asks again when the number was no integer
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
boolean isInputCorrect = false;
do {
System.out.print("input integer #" + (i + 1) + ": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #" + (i + 1) + ": " + intArray[i]);
isInputCorrect = true;
} else {
System.out.println("not an integer, try again");
keyboard.nextLine();
}
} while (!isInputCorrect);
}
keyboard.close();
}
}
Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.
If nothing is put in after java Rev, I need this statement to be printed "Enter only a three digit number, with the first digit larger than the third."
This is not being printed but an error is coming up that says:
x-10-104-10-64:Assgn Katie$ javac Rev.java
x-10-104-10-64:Assgn Katie$ java Rev
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Rev.main(Rev.java:9)
What do I need to fix?
Here is my code:
public class Rev {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
if (checkDigits(num)) {
num = subtractNum(num);
addNum(num);
} else {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}
// checks if numbers are correct
static boolean checkDigits(int number) {
int reverse = reverseNum(number);
if(number < reverse) {
throw new Error("Reverse number needs to be less than the original number!");
} else {
return true;
}
}
//reverses number
static int reverseNum(int number) {
int reverse = 0;
while(number != 0) {
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
// subtracts
static int subtractNum(int number) {
int reverse = reverseNum(number);
int total = number - reverse;
System.out.println("Reverse and subtract: ");
System.out.println(number);
System.out.println(reverse + " - ");
System.out.println("---");
System.out.println(total);
System.out.println();
return total;
}
// adds
static int addNum(int number) {
int reverse = reverseNum(number);
int total = number + reverse;
System.out.println("Reverse and add: ");
System.out.println(number);
System.out.println(reverse + " + ");
System.out.println("---");
System.out.println(total);
return total;
}
}
Check the length of args. Add something like
if (args.length != 1) {
System.err.println("Please provide a single argument.");
System.exit(1);
}
to the start of main.
You are trying to access the 0th element of the args array, which may not exist (if the program is ran without arguments). You should either verify that args has sufficient length before attempting to access the element, or handle the ArrayIndexOutOfBoundsException with a try/catch block.
Use a try/catch block with a print statement inside the catch portion to display that particular message.
public static void main(String[] args)
{
try {
int num = Integer.parseInt(args[0]);
if (checkDigits(num))
{
num = subtractNum(num);
addNum(num);
}
} catch (Exception e) {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}
I'm trying to find the smallest number in a array of 1000 possible slots but my code keeps returning 0 even though 0 is not one of my inputs. My problem is in the last for loop, the rest of the code works. Here is my code:
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SmallestNumber
{
public static boolean isInteger(String num)
{
boolean again=false;
try
{
int d= Integer.parseInt(num);
again=true;
}
catch(NumberFormatException e)
{
again=false;
}
return again;
}
public static void main(String[] args)
{
int [] intNum = new int[1000];
int i=0;
String num;
boolean repeat = false;
String done="done";
Scanner inData = new Scanner(System.in);
System.out.println("You can enter up to 1000 integers." + "\n" + "Enter 'done' to finish");
while (!repeat)
{
System.out.print("Int: ");
num=inData.next();
repeat=isInteger(num);
if (repeat==false)
{
String entry=num.toUpperCase();
boolean equals=entry.equals("DONE");
if (equals==true)
{
repeat=true;
}
else
{
System.out.println("Error: you did not enter a valid chracter. Please enter a interger or state 'done'");
repeat=false;
}
}
else
{
int number=Integer.parseInt(num);
intNum[i]=number;
i=i+1;
if(i<1000)
{
repeat=false;
}
else
{
repeat=true;
}
}
}
int temp=intNum[0];
for(int j=1;j<intNum.length;j++)
{
if (intNum[j]<temp)
{
intNum[j]=temp;
}
else
{
}
}
System.out.print(temp);
}
}
You didn't say how many integers you are actually entering, but the problem is that you're iterating intnum.length times. You've declared your input fields as an array of 1000 elements, length will always be 1000 even if the user has entered fewer integers than that. Once your code has flown past the integers you actually entered, it's going to hit the initialized 0s of the array.
Hi I solved the problem by changing the length of the ending for loop to i and switching
intNum[j]=temp;
to
temp=intNum[j];
Thanks again
The process:
Prompt user
Validate input: IF input NaN skip, ELSE add to ArrayList of Integers
Sort array list in ascending order
Value at index 0 is the smallest
Everything else in your that doesn't fit this process is either out of place or not needed.
UPDATE:
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<Integer>(1000);
Scanner inData = new Scanner(System.in);
System.out.println("You can enter up to 1000 integers." + "\n"
+ "Enter 'done' to finish");
String input = "";
do
{
input = inData.next();
try
{
numbers.add(Integer.parseInt(input));
}
catch(NumberFormatException e)
{
System.out.println(input + " is not a number. Skipping...");
}
} while (!input.equalsIgnoreCase("done"));
Collections.sort(numbers);
inData.close();
System.out.println("Smallest number: " + numbers.get(0));
}
This does exactly what the title suggest without all the extras. It was suggested by David Wallace that might be overkill. I am not sure it is. Don't have time to benchmark. I have to pack for a trip tomorrow. Maybe someone could comment on it.