Alright, so Im new to using a driver to call methods, and so far this is what ive come up with:
public boolean isPalindrome(String s)
{
int begin = 0;
int end = s.length() - 1;
while (begin < end)
{
if (s.charAt(begin) != s.charAt(end))
{
return false;
}
begin++;
end--;
}
return true;
}
How do I get my driver to print out true when they detect the String "Racecar".
Referencing can be done like:
class Palindrome {
public static void main(String[] args) {
Palindrome test1 = new Palindrome();
String str = "Racecar";
System.out.println("result: " + test1.isPalindrome(str.toLowerCase()));
}
public boolean isPalindrome(String s)
{
int begin = 0;
int end = s.length() - 1;
while (begin < end)
{
if (s.charAt(begin) != s.charAt(end))
{
return false;
}
begin++;
end--;
}
return true;
}
}
Output:
result: true
Related
I would like to apologise in advance if im doing something wrong with the code formatting because this is my second time posting here
I have a java assignment due in a couple of days in which the user enters a string and only the integers are collected from it and placed in the array intArray
Now i think i got the logic right in the code below but when i run it in the main, it asks for the string and the boolean, when i enter both it gives me the error
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115"
This is what i entered for example
"Enter a string and true if you want to skip errors or false if you want to skip errors
sdak23
false"
this is my main:
import java.util.Scanner;
public class MainStringToIntArray {
public static void main(String[] args) {
Scanner intut = new Scanner(System.in);
Scanner input = new Scanner(System.in);
StringToIntArray s1 = new StringToIntArray();
System.out.println("Enter a string and true if you want to skip errors or false if you want to skip errors");
s1.scanStringToIntArray(intut.next(), input.nextBoolean());
}
}
import java.util.Arrays;
import java.util.Scanner;
public class StringToIntArray {
private int[] intArray = new int[10];
public StringToIntArray() {
Arrays.fill(intArray, Integer.MIN_VALUE);
}
public int indexOf(int intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == intToFind) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public int indexOf(String intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == Integer.parseInt(intToFind)) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public boolean contains(int intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public boolean contains(String intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public int get(int index) {
if(index < 0 && index > 10) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
public boolean scanStringToIntArray(String s, Boolean skipErrors) {
Boolean result = null;
Scanner input = new Scanner(s);
int l = s.length();
if ((skipErrors)) {
String discard = null;
for (int a = 0; a < l; a++) {
for (int z = 0; z < l; z++) {
if (input.hasNextInt(s.charAt(z))) {
intArray[a] = s.charAt(z);
System.out.println(a);
result = true;
}
else {
discard = discard + s.charAt(z);
}
}
}
}
else {
for (int v = 0; v < l; v++) {
for (int p = 0; p < l; p++) {
if ((input.hasNextInt(s.charAt(p)))) {
intArray[v] = s.charAt(p);
System.out.println(v);
}
else {
System.out.println(v);
result = false;
}
}
}
}
return result;
}
}
The issue is in the get method. It is logically impossible for the index to be both less than 0 and greater than 10; you probably want to use the logical or operator (||). Also, the maximum index of the array is actually 9, as arrays are zero indexed.
public int get(int index) {
if(index < 0 || index > 9) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
There are other logical errors in your code as well. All your indexOf methods should be returning the index where the element was first found instead of the element itself and your else branch is always resetting it to -1 each time it is not found.
I'm writing a program that takes a string and returns a boolean indicating whether the word is alphabetically arranged e.g. abdest, acknow, adempt etc.
My problem is that the program returns no output but just terminates... Please I would really appreciate some corrections.
Here is my code:
public class test{
public static boolean Abecedarian(String s) {
String alp="";
for(char c ='A'; c<='Z'; c++){
alp +=c;
}
if(s.equals(alp)){
return true;
}else
return false;
}
public static void main(String[] args) {
Abecedarian("victor");
}
}
Try with this:
public static void main(String[] args) {
String [] words = {"abdest", "acknow", "adempt" };
for (String word : words) {
System.out.println(" isAbecedarian '"+word+"': "+isAbecedarian(word));
}
}
public static boolean isAbecedarian(String s) {
if (s == null ) throw new IllegalArgumentException("Error");
if (s.length() < 2) return true;
char last = s.charAt(0);
char current;
for (int i = 1; i < s.length(); i++) {
current = s.charAt(i);
if (current < last) {
return false;
}
last = current;
}
return true;
}
output:
isAbecedarian 'abdest': true
isAbecedarian 'acknow': true
isAbecedarian 'adempt': true
So I have the majority of the code written and it works. Except for the iterative method keeps showing that it is not a palindrome regardless of what is typed in. I am at a loss as to how to remedy it here is the code.
//David Crouse Assignment 2
import java.util.Scanner;
public class Assignment2 {
public static boolean loop = false;
//main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Palindrome Checker!");
do{
System.out.print("Enter a string to check if it is a palindrome. ");
System.out.print("Enter x to exit.");
String word = input.nextLine();
word = word.replaceAll("\\s","");
word = word.toLowerCase();
//Exit Program
if(word.equalsIgnoreCase("x")){
System.out.println("End of program. Good Bye!");
System.exit(0);
}
if(iterativePalindromeChecker(word)){
System.out.println("Iterative Result: Palindrome!");
}else{
System.out.println("Iterative Result: Not a palindrome");
}
if(recursivePalindromeChecker(word)){
System.out.println("Recursive Result: Palindrome!\n");
}else{
System.out.println("Recursive Result: Not a palindrome\n");
}
loop = true;
}while (loop == true);
}
//Iterative Method
public static boolean iterativePalindromeChecker(String str){
boolean result = false;
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
result = false;
}
return result;
}
//Recusive Methods
public static boolean recursivePalindromeChecker(String str){
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return recursivePalindromeChecker(str.substring(1,str.length()-1));
return false;
}
}
Your iterative method never sets result to be true. Here's a modified version:
public static boolean iterativePalindromeChecker(String str){
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
return false;
}
}
return true;
}
Your iterative method does not set result = true anywhere, so it really can't help it. Although I think the iterative method could be better overall. Take a close look at what is happening in the recursive one and see if you can implement some of it (like the guard conditions) more closely in the iterative method, and keep in mind that you are not limited to a single index value in a for loop either. e.g.:
public static boolean iterativePalindromeChecker(String str) {
for(int start = 0, end = str.length() - 1; start < end; start++, end--) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
}
return true;
}
I'm guessing someone once told you that a function should only have one return point, and trying to follow that led you to using a mutable result variable which screwed you here. Using break poses the same ostensible problem anyway. Save yourself the headache and just return as soon as you know the answer.
public static boolean iterativePalindromeChecker(String str) {
int begin = 0;
int end = str.length() - 1;
while (begin < end) {
if (str.charAt(begin) != str.charAt(end)) {
return false;
}
begin++;
end--;
}
return true;
}
We were told to implement a method to detect if a string is a palindrome with iteration and recursion. I was successful in implementing the method with iteration but I am getting this error when I try and do it recursively.
Exception in thread "main" java.lang.NullPointerException
at recursion.RecursivePallindrome.isPallindrome(RecursivePallindrome.java:14)
at recursion.RecursivePallindrome.main(RecursivePallindrome.java:44)
I'm currently clueless on what has gone wrong.
package recursion;
public class RecursivePalindrome {
static String word;
public RecursivePalindrome(String a)
{
a = word;
}
public static boolean isPalindrome()
{
int start = 0;
int end = word.length()-1; //Line 14
char a = word.charAt(start);
char z = word.charAt(end);
Character.toLowerCase(a); Character.toLowerCase(z);
if(start >= end)
{
if(Character.isLetter(a) && Character.isLetter(z))
{
if(a == z)
{
a++;
z--;
}
else
return false;
}
else if(!Character.isLetter(a))
start++;
else if(!Character.isLetter(z))
end--;
else
return false;
}
return true;
}
public static void main(String[] args)
{
new RecursivePalindrome("testing");
if(isPalindrome())
System.out.println("Is!");
else
System.out.println("Is not!");
}
}
Try:
public RecursivePalindrome(String a) {
word = a;
}
This code works, but it isn't a recursion!
package recursion;
public class RecursivePalindrome {
static String word;
public RecursivePalindrome(String a) {
word = a;
}
public static boolean isPalindrome() {
int start = 0;
int end = word.length() - 1;
char a = word.charAt(start);
char z = word.charAt(end);
Character.toLowerCase(a);
Character.toLowerCase(z);
while (start < end) {
if (Character.isLetter(a) && Character.isLetter(z)) {
if (a == z) {
start++;
end--;
a = word.charAt(start);
z = word.charAt(end);
} else {
return false;
}
} else if (!Character.isLetter(a)) {
start++;
} else if (!Character.isLetter(z)) {
end--;
} else {
return false;
}
}
return true;
}
public static void main(String[] args) {
new RecursivePalindrome("testing");
if (isPalindrome())
System.out.println("Is!");
else
System.out.println("Is not!");
}
}
Here's a case of me not taking my time. In the constructor I got my assignment mixed up.
public RecursivePalindrome(String a)
{
a = word;
}
with the proper code being
public RecursivePalindrome(String a)
{
word = a;
}
You forgot to initialize word.
You may want to change
a = word;
to
word = a;
if the first string is lexicographically greater than the second string it should return 1,if equal return 0,else -1.It is return 1,-1,0 correctly for some cases,but for this str1 and str2 the return is coming out to be the opposite of the desired output.
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]) {
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1, testcase2);
System.out.println("Result : " + result);
}
// write your code here
public int newCompare(String str1, String str2) {
int l1 = str1.length();
int l2 = str2.length();
int max = 0;
if (l1 <= l2) {
max = l1;
}
else
max = l2;
int count = 0;
for (int i = 0; i < max; i++) {
char ch1 = str1.charAt(i);
char ch2 = str2.charAt(i);
if (str2.charAt(i) > str1.charAt(i)) {
return - 1;
}
if (str1.charAt(i) > str2.charAt(i)) {
return 1;
}
if (l1 == l2) {
if (ch1 == ch2) {
count++;
}
if (count == max) {
return 0;
}
}
}
if (l1 == l2) return 0;
if (l1 > l2)
return 1;
else
return - 1;
}
}
Here's a simplified answer
public class TestStrings {
public static void main(String[] args) {
System.out.println(compare("Mike", "Mike")); // returns 0
System.out.println(compare("Mikee", "Mike")); // returns 1
System.out.println(compare("Mike", "Mikee")); // returns -1
}
public static int compare(String s1, String s2) {
for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 > c2) {
return 1;
} else if (c2 > c1) {
return -1;
}
}
if (s2.length() > s1.length()) {
return -1;
} else if (s1.length() > s2.length()){
return 1;
} else {
return 0;
}
}
}
I used a loop, with the stopping condition as the length of the shortest word. If the words are equal after the length of the shortest word, then the longer word is automatically larger. That's what the if statement at the bottom is for.
you can try:
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]){
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public int newCompare(String str1, String str2){
int l1=str1.length();
int l2=str2.length();
int max=0;
if(l1<=l2)
{
max =l1;
}
else
max=l2;
int count=0;
for (int i =0;i<max;i++) {
char ch1=str1.charAt(i);
char ch2=str2.charAt(i);
if(str2.charAt(i)>str1.charAt(i))
{
return -1;
}
if(str1.charAt(i)>str2.charAt(i))
{
return 1;
}
}
if(l1==l2)
{
return 0;
}else if (l1 < l2){
return -1;
}else{
return 1;
}
}
In this case where String testcase1 = "helloworld" and String testcase2= "hellojavaworld"
your for loop will run from char 'h' to char 'o'(i=0 to i=4) and none of the if conditions inside your for loop will be satisfied and as soon as i gets incremented to 5
//str1.charAt(i)='w' and str2.charAt(i)=j
if(str1.charAt(i)>str2.charAt(i)) //w(ASCII=119) > j(ASCII=106)
{
return 1; //return 1 and control return to the calling function
}
So result=1. Or in short your code is working properly.
You can specify what you want the output to be.