Java palindrome until EOF - java

I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.
Any insight is appreciated
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
String num = scanner.nextLine();
String reverse = "";
while (scanner.hasNextLine())
{
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
num = scanner.nextLine();
reverse = "";
}
System.out.println("\nProgram ended on request");
}
}

This worked for me; unless you need num or reverse outside the while loop it should work.
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
while (scanner.hasNextLine())
{
String num = scanner.nextLine();
String reverse = "";
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
}
System.out.println("\nProgram ended on request");
}
}

I would separate the palindrome test into its' own method. You could do that in a one line method like
public static boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
but I would prefer to iterate the first half of the characters and compare them to the second half in reverse like
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i * 2 <= chars.length; i++) {
if (chars[i] != chars[chars.length - i - 1]) {
return false;
}
}
return true;
}
Then your main can invoke that in an infinite loop (terminating on the lack of input) like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number to check if it is a palindrome:");
if (!scanner.hasNextLine()) {
break;
}
String num = scanner.nextLine();
if (isPalindrome(num)) {
System.out.printf("%s is a palindrome%n", num);
} else {
System.out.printf("%s is NOT a palindrome%n", num);
}
}
System.out.println("Program ended on request");
}

Related

I'm trying to make the code scan for palindrome but I feel like something added in there that isn't needed. New to java so sorry if it make no sense

// I'm looking for any errors or mistakes I made in the code or another way to do it with if-then statements or usage of array. (very new to java)
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
String letter = input.nextLine();
int n = letter.length();
int numberOfLetters = 0;
for (int i = 0; i < letter.length(); i++) {
numberOfLetters++;
}
if(letter.charAt(0) != letter.charAt(n-1)){
String letter2 = letter.toLowerCase();
if (letter2.charAt(0) == letter2.charAt(n - 1)) {
System.out.println("This is a palindrome " + letter);
}
else {
System.out.println("This is not a palindrome " + letter);
}
}
}
}

to check whether a string is palindrome or not using java

import java.util.Scanner;
public class palindrome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String rev;
for(int i=str.length()-1,k=0;i>=0 && k<str.length();i--,k++)
{
rev.charAt(k) = str.charAt(i);
}
if(rev==str)
System.out.println("string is palidrome");
else
System.out.println("string is not palindrome");
}
}
what is wrong with this code?
note: error is showing at the following line of code
rev.charAt(k)=str.charAt(i);
.charAt(k) doesn't return a location, it only tells you what character is there.
Sample code for palindrome program
import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number 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/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

How to I validate so the user only enters integers

Iv'e been trying to get my code to work so that the user can only input integers. However, its keeps crashing when I enter something with characters like "awsd". I've tried using a bool to help, but it only catches negative inputs. Also, the input method must start as an integer, so I cant switch it to a string. Please help.
import java.util.Scanner; // Needed for Scanner class
import java.io.*; // Needed for File I/O classes
public class Reverse {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String Continue = "yes";
int num;
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile();
//file scanner
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR, true));
while (Continue.equals("yes")) {
System.out.print("Enter an integer number greater than 0 :");
num = keyboard.nextInt();
keyboard.nextLine();
if (fileWR.exists())
{
validate(num, output);
}
else
{
fileWR.createNewFile();
}
//option if the user wants to continue
System.out.println("Do you wish to continue?(yes or no): ");
Continue = keyboard.nextLine();
}
output.close();
}
public static void validate(int num, BufferedWriter output) throws IOException {
Scanner keyboard = new Scanner(System.in);
while(!checkNum(num))
{
System.out.print("That is not an integer greater than 0, please try again: ");
num = keyboard.nextInt();
keyboard.nextLine();
}
System.out.print("The original numbers are " + num +"\n");
output.write("\r\nThe original numbers are " + num +"\r\n");
reverse (num, output);
even (num, output);
odd(num, output);
}// end of public static void validate
public static void reverse(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num); //must output result within the void method for it to count as a void method
String result = ""; //otherwise, you cannot output it in the main method.
for (int i = (input.length() - 1); i >= 0; i--)
{
result = result + input.charAt(i)+' ';
}
result = "the number reversed "+ result +"\r\n";
System.out.print(result);
output.write(result);
}// end of public static void reverse
public static void even(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num);
String result = "";
for (int i = 0; (i < input.length()); i++)
{
if (Character.getNumericValue(input.charAt(i)) % 2 == 0)
result = result + input.charAt(i) + ' ';
}
if (result == "") {
result = "There are no even digits" + "\r\n";
} else {
result = "the even digits are "+ result +"\r\n";
}
System.out.print(result);
output.write(result);
}// end of public static void even
public static void odd(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num);
String result = "";
for (int i = 0; (i < input.length()); i++)
{
if (Character.getNumericValue(input.charAt(i)) % 2 == 1)
{
result = result + input.charAt(i) + ' ';
}
}
if (result == "") {
result = "There are no odd digits" + "\r\n";
} else {
result = "the even odd digits are "+ result +"\r\n";
}
System.out.print(result);
output.write(result);
System.out.print("------------------------\n");
output.write("------------------------\n");
}// end of public static void odd
public static boolean checkNum(int num)
{
if(num > 0) {
return true;
}
else {
return false;
}
}
}
You should first get the String, and then try to cast it:
try {
String numStr = keyboard.nextLine();
num = Integer.parseInt(numStr);
//Complete with your code
} catch (NumberFormatException ex) {
System.out.print("That is not an integer");
}

Java; loop stops unexpectedly while deleting a char from string

I want to write a code that deletes a character from a string(stringbuilder)and continue until the loop finishes. when I delete a character in a string the loop which include this string stop immediately.
for(i=1;i<n;i++){
for(j=0;j<x[i].length();j++){
if((x[i].contains(v)) || (x[i].contains(other))){
}
else{
for(m=0;m<u;m++){
for(l=0;l<x[i].length();l++){
System.out.format("d[i][l]%s charat(m)%s \n",d[i][l],v.charAt(m));
if(d[i][l] != v.charAt(m)){
count++;
System.out.println(m);
System.out.format("count:%d\n",count);
}
if(count == x[i].length()){
v.deleteCharAt(m);
others.deleteCharAt(v.length()-m-1);
System.out.format("count%d \n",count);
System.out.format("u%d ",u);
System.out.println(v);
count=0;
}
}
count=0;
}
}
}
}
Here is the code for delete no.of given chars from given String.
import java.util.*;
class Test{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter String : ");
String str=sc.nextLine();
System.out.print("\nEnter No.of Deletion : ");
int n=sc.nextInt();
//convert String char Array
char[] st = str.toCharArray();
if(st.length>n)
{
for(int i=0;i<n;i++)
{
st[i]='\0';
}
}
else{
for(int j=0;j<st.length;j++)
{
st[j]='\0';
}
}
System.out.println("Rest String : "+String.valueOf(st));
}
}

palindrome - how to make main method call the boolean method?

I am trying to get user input and determine if the word is a palindrome or not. The main method should be where all of the print statements are placed.
package help;
import java.util.Scanner;
public class Help {
public static Scanner user_input;
public static void main(String[] args, Iterable<String> lines) {
System.out.print("Enter a word: ");
user_input=new Scanner(System.in);
}
public static boolean istPalindrom(char[] word) {
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
}
I want it to say
if true then System.out.println(The word is a palindrome.)
else System.out.println(The word is not a palindrome.)
I am not sure how to go about this.
Add following lines into main:
if (isPalindrome(user_input))
System.out.println ("The word is a palindrome.");
else
System.out.println("The word is not a palindrome.");
Note: Try to make your indentation better in order to make code easily understandable and for visual purposes :)
Your palindrome test looks good once you fix the indentation, but it's named oddly in English. You have a Scanner, so you can get lines of input. Then call toCharArray() on the String to get the char[] like
public static void main(String[] args) {
System.out.print("Enter a word: ");
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
String line = input.nextLine();
if (isPalindrome(line.toCharArray())) {
System.out.printf("The word %s is a palindrome.%n", line);
} else {
System.out.printf("The word %s is not a palindrome.%n", line);
}
}
}
public static boolean isPalindrome(char[] word) {
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
This solution might work:
public static void main(String[] args, Iterable<String> lines) {
user_input = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = user_input.nextLine();
if(istPalindrome(word.toCharArray()){
System.out.println("The word is a palindrome");
}else{
System.out.println("The word is not a palindrome");
}
}
The code for palindrome as simple as this if you want to use it !
public static boolean isPalindrom(String word) {
if(new StringBuilder(word).reverse().toString().equals(word)){
System.out.println("The word is a palindrome.");
} else {
System.out.println("The word is not a palindrome.");
}
}

Categories

Resources