check palindrome in java code - eclipse

I'm making a really simple app in java code, but for some reason it doesnt work. its a palindrome checker.
here is the code.
MAIN:
public class main {
public static void main(String[] args) {
Palindroom.palindroomChecker("RACECAR");
}
}
`Palindroom class:
public class Palindroom {
public static void palindroomChecker(String input) {
String omgekeerd = "";
boolean isPalindroom = false;
int length = input.length();
for(int i = 0; i < length; i++ ) {
String hulp = "" + input.charAt(i);
omgekeerd = omgekeerd + hulp;
}
System.out.println(omgekeerd);
System.out.println(input);
if(omgekeerd.equals(input)){
System.out.println("DIT IS EEN PALINDROOM!");
}
else {
System.out.println("HELAAS, DIT IS GEEN PALINDROOM!");
}
}
}`
For some reason the check in the if-statement doesnt go as it has to go. As you can see i checked omgekeerd and input and i also checked earlier the length of omgekeerd to see if there were clear spaces.
Can someone help me out!
thanks in advance
greetings Mauro Palsgraaf

Your logic is flawed. You're reconstructing a new string by appending every char of the input, in the same order, and then check that both strings are equal. So your method always says that the input is a palindrome.
You should construct a new string by appending the chars in the reverse order.
Or you could make it faster by checking that the nth character is the same as the character at the length - 1 - n position, for each n between 0 and length / 2.

You are not actually reversing the string, looks like omgekeerd will be in the same order as input.
Replace for with for(int i = length-1; i >= 0; i--) {

This can be simplified a lot
boolean isPalindrome = new StringBuilder(input).reverse().equals(input);

Maybe this would work for you?
String str = "madam i'm adam."; // String to compare
str = str.replaceAll("[//\\s,',,,.]",""); // Remove special characters
int len = str.length();
boolean isSame = false;
for(int i =0; i<len;i++){
if(str.charAt(i) == str.charAt(len-1-i)){
isSame = true;
}
else{
isSame = false;
break;
}
}
if(isSame){
System.out.print("Equal");
}
else{
System.out.print("Not equal");
}

i=0;
j=str.length()-1; //length of given string
String str; // your input string
while((i<j)||(i!=j)){
if(str.charAt(i)!=str.charAt(j)){
System.out.println("not palindrome");
break;
}
i++;
j--;
}
System.out.print("palindrome");
//this can used for checking without the need of generating and storing a reverse string

Related

Dart find the capital word in a given String

How can I write a code that finds capital words in a given string in dart
for example
String name ='deryaKimlonLeo'
//output='KL'
Hmmm try this using pattern if you only want to get only the big letter then try this
String name ='deryaKimlonLeo';
print(name.replaceAll(RegExp(r'[a-z]'),""));
//Output you wanted will be
// KL
try this on dart pad it works
A basic way of doing this is like
void main() {
String name = 'deryaKimlonLeo';
String result = '';
for (int i = 0; i < name.length; i++) {
if (name.codeUnitAt(i) <= 90 && name.codeUnitAt(i) >= 65) {
result += name[i];
}
}
print(result);
}
More about ASCII and codeUnitAt.
sample code:
void main() {
String test = "SDFSDdsfdDFDS";
for (int i = 0; i < test.length; i++) {
if (test[i].compareTo('A') >= 0 && test[i].compareTo('Z') <= 0)
print(test[i]);
}
}

Flutter: Get the position of all the letters. (Game)

I'm making a game, but I can't change the letter that matches more than once.
I don't know what I'm doing wrong, I hope someone can help me, thanks.
I leave a demonstration video, the result of the word is DOMINGO
The problem I perceive is that when I press the key or it is assigned only at the beginning.
When it must be completed with all possible matches.
YouTube Video Here
This is my dart function.
String word = 'domingo';
String key = 'o'; // OnTap button "O"
List<Word> positionsFound = List<Word>();
_word(){
String wordEmpty = '';
for(int i=0; i<word.length; i++){
if(key.isEmpty){
wordEmpty = wordEmpty+'_';
} else {
wordEmpty = wordEmpty+'_';
int position = word.toLowerCase().indexOf(key.toLowerCase());
if(position == i){
positionsFound.add(Word(key, position));
print(position); // The position must be 1 and 6, it only gives me 1.
}
}
}
for(int i=0; i<positionsFound.length; i++){
wordEmpty = wordEmpty.replaceFirst('_', positionsFound[i].key, positionsFound[i].position);
}
return wordEmpty;
}
class Word {
String key;
int position;
Word(this.key, this.position);
}
After a while, I realized that indexof allows you to start from the last search you performed.
if(key.isNotEmpty){
int position = word.toLowerCase().indexOf(key.toLowerCase());
while(position != -1){
if(position != -1){
positionsFound.add(Word(key, position));
}
position = word.toLowerCase().indexOf(key.toLowerCase(), position+1);
}
}

How to use selection sort in objects and classes

I'm creating two classes called stop watch and random numbers, which I have already done, but I needed to create a test program that would measure the execution time of sorting 100,000 numbers using selection sort. I know how to create a selection sort, I just don't know how to take the random numbers class and put it together with the selection sort, I get the error message "incompatible types random numbers cannot be converted to int" I hope someone can help me.
My random numbers class
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
My test Program
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
Where exactly are you getting "incompatible types random numbers cannot be converted to int" error?
There are multiple issues with the code:
Unconventional naming
size field is in randomnumbers class is used as actual array size in constructor but in createArray it's overshadowed with a parameter of the same name but different type and meaning.
You are not passing any array to selectionSort in Main. This is where I get compile error on your code.
printArray has if (i < 0) condition that is false for all ran1.nextInt() numbers so it will not print anything.
Feeding selectionSort with numbers.createArray(new int[numbers.getSize()]) compiles and ends up sorting the array.

ASCII conversion

I wanted to convert ASCII values to its corresponding characters so I wrote this simple code:
public class Test {
public static void main(String[] args) {
int i=0;
char ch='c';
for(i=0;i<127;i++)
{
ch=(char)i;
System.out.print(ch+"\t");
}
System.out.println("finish");
}
}
But as output it's showing nothing and along with that the control is not even getting out of the loop though the process gets finished..plz explain this kind of behavior and the right code.
As other people have pointed out, you have included the control characters; if you alter the loop (as below) you get the full set, excluding these control characters:
public static void main() {
for(int i = 33; i < 127; i++)
{
char ch = (char) i;
System.out.print(i + ":" + ch + "\t");
}
System.out.println("finish");
}

While/if Loop is not working in class

I'm learning java and I'm having an issue with my if code not running.
In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.
I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 45;
int tri = 0;
int triplus = 0;
String triresult;
public String triangle() {
while (tri < num) {
if (tri == num) {
triresult = "Is a Triangle";
System.out.println("Is a Triangle");
} else if (tri + (triplus + 1) > num){
triresult = "Is Not a Triangle";
} else {
triplus++;
tri = tri + triplus;
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Thanks for any help provided.
Try this code :
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 10;//Try other numbers
int tri = 0;
int triplus = 0;
int res = 0;
String triresult = "Is Not a Triangle";
int[] tab= new int[num];
public String triangle() {
//to calculate the triangle numbers
for(int i = 0; i<num; i++){
res = res + i;
tab[i]=res;
}
//To check if num is a triangle or not
for(int i = 0; i<tab.length; i++){
System.out.println(">> " + i + " : " + tab[i]);
if(tab[i]== num){
triresult = num + " Is a Triangle";
break;//Quit if the condition is checked
}else{
triresult = num + " Is Not a Triangle";
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Hope this Helps.
Step through the loop carefully. You'll probably see that there is a case where
(tri < num)
fails, and thus you fall out of the loop, while
(tri == num)
and
(tri + (triplus + 1) > num)
both fail too, so no text gets set before you fall out.
You probably want to do your if-tests within the method on just tri, not a modification of tri, so as to reduce your own confusion about how the code is working.