Check string if Symmetrical and palindrome - java

I just go the Symmetrical at makeuseof and it's currently in javascript and i converted it to Java, However there's an error on the line 38 which is the array. Please check the code below, Thank you.
import java.util.Scanner;
class check
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
//Check if Symmetrical
if (isSymmetrical(str)) {
System.out.println(str +" is a symmetrical");
} else {
System.out.println(str +" is not a symmetrical");
}
//Check if palindrome
if (str.equals(rev))
System.out.println(str +" is a palindrome");
else
System.out.println(str +" is not a palindrome");
}
public static boolean isSymmetrical(String str){
double midIndex;
var length = str.length();
if (length % 2 == 0) {
midIndex = Math.floor(length/2);
}
else {
midIndex = Math.floor(length/2) + 1;
}
var pointer1 = 0;
var pointer2 = midIndex;
while(pointer1 < midIndex && pointer2 < length) {
if(str[pointer1] == str[pointer2]) {
pointer1 += 1;
pointer2 += 1;
}
else {
return false;
}
}
return true;
}
}
Error:

Thanks to for sharing the String::charAt this is very helpful
I used charAt and convert double to int.
import java.util.Scanner;
class check
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
//Check if Symmetrical
if (isSymmetrical(str)) {
System.out.println(str +" is a symmetrical");
} else {
System.out.println(str +" is not a symmetrical");
}
//Check if palindrome
if (str.equals(rev))
System.out.println(str +" is a palindrome");
else
System.out.println(str +" is not a palindrome");
}
public static boolean isSymmetrical(String str){
double midIndex;
int length = str.length();
if (length % 2 == 0) {
midIndex = Math.floor(length/2);
}
else {
midIndex = Math.floor(length/2) + 1;
}
int pointer1 = 0;
double pointer2 = midIndex;
while(pointer1 < midIndex && pointer2 < length) {
if(str.charAt(pointer1) == str.charAt((int)pointer2)) {
pointer1 += 1;
pointer2 += 1;
}
else {
return false;
}
}
return true;
}
}
Output:

Related

Making an Armstrong number checker but if condition is not working

I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}

How to check if the System.in contains only numbers

Have a task to get N numbers from console, find the longest and the shortest ones and their length. The task is not difficult and works correctly, but I decided to make a check, if the console input corresponds the conditions of the task:
Are there only Integer numbers.
Are the exactly N numbers, not more/less.
I decided to write a boolean method isInputCorrect(), which would take the Scanner and check if the input is correct, but it doesn't work correctly.
public static void main(String[] args) {
int n = 5;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Hello, please enter " + n + " integer numbers:");
while (!isInputCorrect(sc,n)){
System.out.println("Wrong! Try again:");
sc.next();
}
} while (!isInputCorrect(sc, 5));
String scLine = sc.nextLine();
String[] arr = scLine.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isInputCorrect(Scanner sc, int n){
boolean flag = true;
for (int i = 0; i < n; i++){
if (sc.hasNextInt()){
sc.next();
}else {
flag = false;
break;
}
}
return flag;
}
EDIT
This code still doesn't work. I realize, that the problem is in isDigit(). And exactly in regular conditions in last if statement. It is something like this:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
This method takes the console input as a string, then it checks, how many numbers(strings) does it contain, are there any negative numbers and so on. But it can be applied only for substrings(words without whitespace). In my case it can be applied to arr[i].
So I modified it to split String into array[] and tried to check every single element. I've got:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
but it returnes true even when input is:
1 3213 w 15 3
I can't understand, what is the problem? The full code is:
public static void main(String[] args) {
int n = 5;
boolean validInput = false;
String input;
do {
System.out.println("Please enter " + n + " integer numbers:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
if (isDigit(input, n)) {
validInput = true;
} else {
System.out.println("Wrong input! Try again: ");
}
}
while (!validInput);
String[] arr = input.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
SOLVED
Thanks to everybody, your help was really usefull. I finally found the problem
It was in isDigit() method. It was checking out every element of array, and switched a flag according to the last result. I wrote "break" to stop the further checking if there was at least one false flag in loop.
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else{
for (String s: arr){
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
else {
if (s.matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
}
}
return flag;
}
You may use regular expressions to verify that the input contains only integer numbers:
int n = 5;
// ... your current code
String scLine = sc.nextLine();
if (!scLine.matches("\\d+(?:\\s+\\d+)*")) {
throw new IllegalArgumentException("input contained non-integers");
}
String[] arr = scLine.split("\\s+");
if (arr.length != n) {
throw new IllegalArgumentException("found " + arr.length + " number inputs but expected " + n + ".");
}
you can check if input string has only numbers as below
public boolean isDigit(String input) {
if (input == null || input.length() < 0)
return false;
input = input.trim();
if ("".equals(input))
return false;
if (input.startsWith("-")) {
return input.substring(1).matches("[0-9]*");
} else {
return input.matches("[0-9]*");
}
}
EDIT:
allowing user to re-enter untill valid number is entered
boolean validInput = false;
do
{
System.out.println("Enter the number ");
// get user input
String input sc.nextLine();
if(isDigit(input))
validInput = true;
else
System.out.println("Enter valid Number");
}
while (!validInput );

Comparing Two Strings One Character at a Time in Java

I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE

Changing my program to use ArrayList

So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}

Creating a Palindrome identifier

How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)

Categories

Resources