import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i;
String A=sc.next();
String B= "";
/* Enter your code here. Print output to STDOUT. */
for(i=A.length()-1;i<=0;i--){
B = B+A.charAt(i);
}
if(A.equals(B)){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
I'm not getting the required output for my code. I'm a beginner in Java.
The reason your program isn't giving you the desired output is because your for-loop is incorrect.
for(i.A.length()-1; i <= 0; i--) {/.../}
You are basically saying, whilst i is less than or equal to zero, execute the loop. i by default is greater than 0.
You can achieve a Palindrome check multiple ways. 2 Examples.
Example 1 using for-loop:
String A = "radar";
String B = "";
for(int i = A.length()-1; i >= 0; i -- ){
B = B + A.charAt(i);
}
System.out.println(A.equals(B) ? "Yes" : "No");
Example 2 with StringBuilder.
String A = "radar";
StringBuilder B = new StringBuilder(A).reverse();
System.out.println(A.equals(B) ? "Yes" : "No");
You are constantly getting an output of "No" because you're checking if i is less than or equal to zero on each loop, while you should be checking for greater than or equal to.
Change for (i = A.length() - 1; i <= 0; i--)
to
for (i = A.length() - 1; i >= 0; i--)
The for loop runs as long as the condition holds, in your case i<=0.
Unless the input has length 0 this condition never holds, thus the body of the for loop never gets executed and you immediately skip to if(A.equals(B))... which will always be false (except for the input "").
It should be i>=0.
Related
I'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) {
if(finale.substring(i, i) == " ") {
i += 2;
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
Any help?
You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.
Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
finale.insert(i++, " ");
}
The output: T H I S F O N T
For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
// Code to be executed during each pass of the loop
}
First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
Everything inside the brackets is, obviously, the code we want to execute on each loop.
You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.
Some issues with your code (see inline comments):
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) { // this condition is incorrect. Initially
// this condition will always be false
// if you input some sentence. It should be
// i < finale.length()
if(finale.substring(i, i) == " ") { // here preferably you should use
// equals method to compare strings
i += 2;
// you are only incrementing the i if the ith
// substring equals " ". Firstly, substring(i,i)
// will return empty string because the second argument
// is exclusive
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
System.out.println(finale);
}
}
First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
Here is a sample run:
Input text here: This is a sentence
T H I S I S A S E N T E N C E
The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
finale.insert(i, '\t');
i += 2;
}
An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
finale.append(c).append('\t');
}
Use a for loop since you know the number of iterations:
Scanner input = new Scanner(System.in);
String x;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
int len = finale.length();
for (int i = 1; i < 2 * len; i+=2 ) {
finale.insert(i, '\t');
}
System.out.println(finale);
You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
.filter(i -> i != ' ')
.mapToObj(t -> (char) t)
.map(Character::toUpperCase)
.map(Character::valueOf)
.collect(Collectors.joining(" ");
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word;
String c;
int x, count, count1;
System.out.println("Please enter a word:");
word=in.nextLine();
x=word.length();
for(count=0;count<x;count++) {
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
}
}
}
All this program does is print out the second to last character of the word that the user enters. I'm confused as to why it is doing this and want to know how to print out the whole word backwards. Someone help please.
You don't need a loop to reverse a string.
Ref - StringBuilder#reverse
Scanner in = new Scanner(System.in);
System.out.println(new StringBuilder(in.nextLine()).reverse());
If you want to print characters in reverse, then forget the substring-ing.
String word = in.nextLine();
int x = word.length();
for(count = x - 1; count >= 0; count--) {
System.out.println(word.charAt(count));
}
Take count1=x; assignment out of the loop. Also make count--; after printing the letter.
You are correct up until x = word.length(). It is printing the second from last character because you keep setting the value of count1 to length of word and you substract it by 1. Therefore, it keeps referring to the second last character. To fix that, do the following instead:
count1=x;
for(count=0;count<x;count++) {
c=word.substring((count1)-1,count1);
System.out.println(c);
count1--;
}
Every time the loop is running, you are resetting the count1 value to x (count1=x). So c will always be the same value.
To make this work, try taking count1 = x out of the loop so that every time the loop is running, count1 value will be reduced as expected providing the required sub-string.
Into the loop for(count=0;count<x;count++)
Every loop you did the same thing
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
This block has no relation with the loop!
Thats why you are getting the second last character!
To fix this:
Solution 1: (Just reverse the String)
word=in.nextLine();
System.out.println(new StringBuilder(word).reverse());
or Solution 2: (Using loop using your code)
x=word.length();
for(count= x-1; count >= 0; count--) {
c = word.substring((count)-1, count);
System.out.print(c);
}
If at all you want to do it the hard way by traversing, do the following changes.
for(count=x;count>=0;count--) {
System.out.println(word.substring(count - 1,count));
}
Update: You can use charAt#String to easily get the character at some position.
for(count=x-1;count>=0;count--) {
System.out.println(word.charAt(count));
}
I am writing this program for school work that asks the user to input a sequence of letters and numbers and determine whether it is a digit or not.
My teacher wants me to add up the characters that are digits(numbers) and output it as "Your numbers added up together are: place added number here"
and output the letters are a string saying "These are your letters: *place letters here."
I think I got the code right that determines whether it is a digit or not but how do I end up adding them? I tried using an if statement that checked if Character.isDigit is true but I keep getting errors and I think I'm writing it totally wrong. Any response would be greatly appreciated.
Here is my code:
import java.util.*;
import java.util.Scanner;
public class MyClass
{
public static void main(String args[])
{
int sum1 = 0;
String stringFull = "";
boolean isTrue = Character.isDigit(string1.charAt(i));
Scanner getString = new Scanner(System.in);
System.out.println("Please enter a sequence of letters: ");
String string1 = getString.nextLine();
for(int i = 0; i < 5; i++)
{
if (Character.isDigit(string1.charAt(i)))
{
sum1 += Character.getNumericValue(string1.charAt(i));
} else {
stringFull += string1.charAt(i);
}
if (isTrue)
{
System.out.println(sum1 * sum1);
}
}
}
}
You will get compilation error for below as i wasn't declared before this line
boolean isTrue = Character.isDigit(string1.charAt(i));
instead you should initialize it with false
boolean isTrue = false;
Then, your loop should loop till given string length, but you have hard-coded to 5, which will cause exception at runtime when string length is less than 5.
for(int i = 0; i < 5; i++)
should change to
for(int i = 0; i < string1.length(); i++)
Also, inside you for loop you are have following line of code, but you have never changed isTrue value inside the loop.
if (isTrue)
{
System.out.println(sum1 * sum1);
}
And, I think, right place to change isTrue value, where you are checking for digit.
if (Character.isDigit(string1.charAt(i)))
{
sum1 += Character.getNumericValue(string1.charAt(i));
isTrue = true;
}
You should use
Integer.parseInt(String.valueOf(string1.charAt(i)))
which returns the number, instead of
Character.getNumericValue(string1.charAt(i))
which returns the ascii code for the number
I'm learning Java. I'm building this Palindrome recognizer and using two arrays with chars, I think I got a good implementation with other things I've found around but I'm breaking my head to understand why it's not working as intended so far. What is happening:
"A Santa at Nasa", palindrome, checks as a palindrome.
"I don't know, anything", not a palindrome, checks as not a palindrome.
"Not a palindrome", not a palindrome, checks as a palindrome.
I basically need some help to understand where exactly I got it wrong on my code. Thanks!
/*
"A Santa at Nasa" is an example of palindrome.
*/
import java.util.Scanner;
public class Palindrome
{
public static void main (String[] args)
{
boolean isPalindrome = false;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a string:");
String userInput = kb.nextLine();
userInput = userInput.trim().replaceAll(" ", "").toLowerCase();
char[] array = new char[userInput.length()];
char[] reverseArray = new char[userInput.length()];
int i = 0;
int j = userInput.length();
do {
i++;
j--;
array[i] = userInput.charAt(i);
reverseArray[j] = userInput.charAt(j);
if (array[i] != reverseArray[j])
{
isPalindrome = false;
}
else
{
isPalindrome = true;
}
} while (j > i);
if(isPalindrome)
{
System.out.println("It's a palindrome.");
}
else
{
System.out.println("Not a palindrome.");
}
}
}
Once you've established that the input is not a palindrome, you should end the test.
Currently your algorithm is allowed to change its mind!
You are also incrementing i prematurely.
Here's the problem, you must start before the first element of the input array, because you do a i++ at the beginning of your loop:
int i = -1;
Also, the exit condition of your loop can be improved, so it exits earlier:
while (j > i && !isPalindrome);
Are you allowed to use StringBuilder? If so, you can do String reverseText = new StringBuilder(userInput).reverse().toString();
If not, why not try iterating through the array once and then compare at the end? Leave your array and reverseArray initializers as they are, but then do a for or while loop after that just faithfully copies from the userInput variable into the correct locations in both the arrays.
Then you can just use a single comparison at the end to decide what to print.
A couple things.
You should do your index changes at the end of your loop, to fix starting the lower index from 1.
With the previous change, you should start your upper index from userInput.length()-1 as that will then be the first index from the top that you check.
You should stop when you find one mismatch, as otherwise with a string of odd length, your result will always be the check of the middle character against itself (and otherwise your result will end up being the check of the two middle characters of an even string against each other).
If you'd like the full re-worked solution, I can post it, but you can probably fix it yourself from here!
Well, the problem is that you set your isPalindrome every time you check two letters. So when the last 2 letters checkt are the same, it will say it is a palindrome. Instead try this:
import java.util.Scanner;
public class Main
{
public static void main (String[] args)
{
boolean isPalindrome = true;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a string:");
String userInput = kb.nextLine();
userInput = userInput.trim().replaceAll(" ", "").toLowerCase();
char[] array = new char[userInput.length()];
char[] reverseArray = new char[userInput.length()];
int i = 0;
int j = userInput.length() - 1;
while(i < j && isPalindrome) {
array[i] = userInput.charAt(i);
reverseArray[j] = userInput.charAt(j);
if (array[i] != reverseArray[j])
isPalindrome = false;
i++;
j--;
}
if(isPalindrome)
System.out.println("It's a palindrome.");
else
System.out.println("Not a palindrome.");
}
}
So now the isPalindrome boolean is set to true in the beginning, and when we find something that contradicts this (two characters that are not the same) it will set isPalindrome to false.
I have not tested this code, so there could be some other error. But this is the one I saw at first glance.
EDIT: i didn't start from the beginning of the string. And best to use a while instead of do while because the string could be empty.
I have the following code and i want to print the palindrome on console. Please let me know what should come inside the if condition so that it can print all palindrome in between 0 to 10000.
The palindrome is 161, 1221, 4554, etc....
Java code:
int palindrome[];
palindrome = new int[10000];
for (int count = 0; count < palindrome.length; count++ ){
palindrome[count] = 0;
if(){
System.out.println(count);
}
}
This will do:
if (isPalindrome(count)) {
System.out.println(count);
}
...
public boolean isPalindrome(int num) {
// implement method here (ie: do your homework)
}
Something like this might work
public boolean isPalindrome(final int num) {
final String s = Integer.toString(num);
return s.equals(new StringBuffer(s).reverse().toString());
}
You need to transform the number into a string and then check if the string reversed is equal to the original string. This looks a lot like some homework, if so please add the appropriate tag.
The code golf solution:
public static boolean isPalindrome(int number) {
return ("" + number).equals(new StringBuilder("" + number).reverse().toString());
}
You could also reverse the number and check if the reversed one and your number are equal.
To reverse the number: keep dividing it with 10 until the result is 0. Save the remainders of the divisions. Starting from the first remainder you get, multiply it by 10 and add the next remainder. Keep multiplying by 10 and adding remainders till you use all the remainders.
To revers I use a StringBuffer, StringBuffer(num).reverse().toString();
Here are some hints:
a) To get the last digit of a number use the remainder (%) operator
Example:
result = number % 10; // 21 % 10 = 1
b) To cut of the last digit, divide by 10
Example:
number = number / 10; // 21 / 10 = 2;
c) Multiply the result by 10
Example:
result = result * 10; // 1 * 10 = 10
d) Repeat until some condition is fulfilled (shouldn't be too hard to figure out ;-))
boolean isPalin(int n)
{
String s = Integer.toString(n);
return s.equals( new StringBuffer(s).reverse().toString() );
}
so your if condition should contain: isPalin(count)
boolean isPalin(int n)
{
int nn = 0, tmp = n;
while(n > 0)
{
nn = nn*10 + n%10;
n /= 10;
}
return tmp==nn;
}
I prefer doing it this way instead of using strings, since strings make the process slow as it involves a lot of overhead.
import java.util.*;
import java.io.*;
public class TestFinal {
public static Scanner c = new Scanner(System.in);
public static void main(String[] args) {
String original ,reverse ="";
// TODO, add your application code
System.out.println("Enter the text!");
original = c.next();
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 strig is a palindrome");
else
System.out.println("the text is not a palindrome");
}
}
An easy way to print palindrome:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
/* Enter your code here. Print output to STDOUT. */
int len = A.length();
String B ="";
for(int i=len-1;i>=0;i--){
B=B+A.charAt(i);
}
if(A.equals(B))
System.out.println("Yes");
else
System.out.println("No");
}
}