This project is used to identify whether or not a user's input is a palindrome, and if it's not, identifies how many characters don't match and their positions in the string (i.e characters 2 and 4 don't match). I've been able to figure out how to identify whether or not a string is a palindrome, but I'm struggling with how to specifically identify the characters that don't match in a non-palindrome. Here's my code so far:
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
String stringInput = "";
String inputReverse = "";
boolean isPalindrome = true;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
stringInput = keyboard.nextLine();
int stringLength = stringInput.length();
for(int i = stringLength - 1; i >=0; i--)
{
inputReverse = inputReverse + stringInput.charAt(i);
}
if(stringInput.equals(inputReverse))
{
System.out.println(stringInput + " is a valid palindrome.");
}
else
{
System.out.println(stringInput + " is not a valid palindrome.");
}
}
}
the output I want for when a string is not a palindrome is:
"The characters at index 0 and 3 do not match.
goop is not a valid palindrome.
number of invalid character matches: 1 "
I tried to use stringInput.charAt(0) but the user input is unpredictable, so I wouldn't be able to use char 0,1,2,3 etc forever. Any help?
Iterate from both ends of the string, moving toward the center and checking the corresponding characters each time.
int nomatch = 0;
for (int i = 0, j = stringLength - 1; i < j; i++, j--) {
if (stringInput.charAt(i) != stringInput.charAt(j)) {
++nomatch;
System.out.format("The characters at index %d and %d do not match.%n", i, j);
}
}
if (nomatch == 0) System.out.println(stringInput + " is a palindrome.");
else System.out.println(stringInput + " is not a palindrome. Number of invalid character matches: " + nomatch);
As this is home work, I'll only give general hints:
an easy way to reverse a string is inputReverse = new StringBuilder(stringInput).reverse().toString();
you only need to compare each character of the first half of the input with its reverse
use a for loop of int from 0 to half the length and pass it to charAt() for both strings and compare using ==
store the indexes of differences in a List<Integer>
Related
So, I'm meant to get two version of a word given by user input, a version with just the lower case letters and then a version with just the upper case letters. Im then meant to find out if both of the words are palindromes. For example if the word was 'HEllO', the words HEO and ll would be created and then the output "HEO is not a palindrome, ll is a palindrome" would be printed. Im pretty sure my code makes sense but it won't say if either version of the original word is a palindrome. The following is the code.
public class comp1
{
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String lower = lowerCaseLetters(input);
String upper = upperCaseLetters(input);
palindromeUpper(upper);
palindromeLower(lower);
}
public static String lowerCaseLetters(String input)
{
char[] ar = new char[input.length()];
for(int i = 0; i < input.length(); i++)
{
if(Character.isLowerCase(input.charAt(i)))
{
ar[i] = input.charAt(i);
}
}
String lowercase = new String(ar);
return lowercase;
}
public static String upperCaseLetters(String input)
{
char[] ar = new char[input.length()];
for(int i = 0; i < input.length(); i++)
{
if(Character.isUpperCase(input.charAt(i)))
{
ar[i] = input.charAt(i);
}
}
String uppercase = new String(ar);
return uppercase;
}
public static void palindromeUpper(String sent)
{
String reverse = "";
for(int i = sent.length()-1; i >= 0; i--)
{
reverse += sent.charAt(i);
}
if(sent.equals(reverse))
{
System.out.println("Upper case " + sent + " is a palindrome");
}
else
{
System.out.println("Upper case " + sent + " is not a palindrome");
}
}
public static void palindromeLower(String sent)
{
String reverse = "";
for(int i = sent.length()-1; i >= 0; i--)
{
reverse += sent.charAt(i);
}
if(sent.equals(reverse))
{
System.out.println("Lower case " + sent + " is a palindrome");
}
else
{
System.out.println("Lower case " + sent + " is not a palindrome");
}
}
}```
arrays don't skip 'empty' values. In fact, there's no such thing as an empty slot; char[] ar = new char[input.length()]; gives you a char array with length slots, and each slot is filled with an actual character: The NUL character.
You then copy over all lowercase letters to their appropriate position, which means all non-lowercase letters still have the NUL character. You then turn this back into a string, which will be a string with lots of NUL characters, and those NUL characters will then prevent the rest of your code from working properly; ll is a palindrome, sure. but \0\0ll\0 is not.
You can't resize arrays, you need to create them at the right size. Thus, you have two options:
loop through the string twice. First time, you just count lowercase letters, that is all you do. Second time, you copy over the lowercase letters, and not to position i, but to a counter you maintain (the first l occurs at i=2, but needs to go into ar[0]. The second l occurs at i=3, and needs to go into ar[1]).
Don't use a char array; use a StringBuilder instead, which grows on demand. just .append any lowercase letters.
2 is probably easier, but involves the use of another class (java.lang.StringBuilder).
Note then that your palindromeLower and palindromeUpper methods are identical, other than the messaging.
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string
I have looked on other such answers with this error and I can't seem to figure out my code specifically. I am using Java, and I am trying to make a program where I enter a number as an input, and as an output I should get:
example input: 1234
The original number is 1234
The number in reverse is 4 3 2 1
I have this code written:
import java.util.Scanner; //Needed for Scanner class
public class CoeQuiz3
{
public static void main(String[] args)
{
//establish variables
String ogNumber;
int ogNumberInt;
Scanner keyboard = new Scanner(System.in); //establish scanner
System.out.println("Enter a positive integer greater than 0.");
ogNumber = keyboard.nextLine();
ogNumber = checknumber(ogNumber);
ogNumberInt = Integer.parseInt(ogNumber);
//print the original number
System.out.println("The original number is " + ogNumber);
//print the reverse number
int ogNumberLength = ogNumber.length();
int digitposition, ogDigit;
String reverseStatement = "The number reversed is ";
for (digitposition = ogNumberLength; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
System.out.println(reverseStatement);
it compiles and runs, but every time it gives me the error:
The original number is 1234
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:658)
at CoeQuiz3.main(CoeQuiz3.java:30)
It should work logically - what is the problem? This problem still occurs if I replace >= with >.
You are trying to access one past the highest available character index in your string. Try this loop instead:
for (int i=ogNumber.length()-1; i >=0; i--) {
char chr = ogNumber.charAt(i);
reverseStatement += chr;
}
System.out.println(reverseStatement);
But a nicer way to do this is to use the StringBuffer.reverse() method:
String ogNumberReversed = new StringBuffer(ogNumber).reverse();
for (int i=0; i < ogNumberReversed.length(); ++i) {
char chr = ogNumberReversed.charAt(i);
reverseStatement += chr;
}
System.out.println(reverseStatement);
Alternative solution:
int number = 1234;
String strReversed = new StringBuilder(String.valueOf(number)).reverse().toString().replace("", " ").trim();
System.out.println(strReversed); // 4 3 2 1
Ideone example
See this piece of code
for (digitposition = ogNumberLength; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
The first parameter of the loop digitposition = ogNumberLength
specifies that the loop should access the char at the position equal to length of the string, and in case of string, the length is equal to the number of characters (for e.g. length of string "HAPPY" would be 5 not 4). But the index of the last element of the String array is one less than the length of the string (as arrays are zero indexed).
So in practice if you have entered the number "1234":
length of string is = 4
position of last element array = 3
So your code is trying to access the element number 4 in an array of last index 3, hence the exception.
You should instead write the following (notice the -1 in the 1st parameter)
for (digitposition = ogNumberLength - 1; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
This would solve your problem, however if reversing only numbers is your sole objective then I would suggest use the following method as using strings is much more resource intensive
import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of entered number is "+reverse);
}
}
Cheers!!!
Please change your for-loop as follows:
for (digitposition = ogNumberLength-1; digitposition >= 0; digitposition--){
ogDigit = Character.getNumericValue(ogNumber.charAt(digitposition));
reverseStatement += ogDigit + " ";
}
and see the results.
There are two things which have been added:
The for loop counter should start from ogNumberLength-1 not
ogNumberLength. This was the reason for
java.lang.StringIndexOutOfBoundsException
There is a need to convert the ASCII value of char to number. That is why
Character.getNumericValue() has been used.
Hope, it helps!
I would like to compare two user-defined strings and output the count of the number of characters shared between the two strings, without resorting to using arrays. I then need to output each of those characters. I understand the user-input part using a Scanner, but afterwards I am clueless.
For example, "hamper" as string1, and "happened" as string2 would return:
number of shared characters = 5
shared characters >> "h", "a", "p", "p", "e", "e"
Here is what i have so far. It prints each character on a separate line though. Is there a way without arrays to list them all on one line like above?:
public class CountMatches {
public static void main(String[] args)
{
//Declare both Strings.
String word1;
String word2;
int count = 0;
//Call for User Input.
Scanner inputDevice = new Scanner(System.in);
System.out.print("Input String 1 >> ");
word1 = inputDevice.next();
System.out.print("Input String 2 >> ");
word2 = inputDevice.next();
inputDevice.close();
//Determine lengths and set label accordingly.
String BigWord;
String SmallWord;
if (word1.length() > word2.length())
{
BigWord = word1;
SmallWord = word2;
}
else
{
BigWord = word2;
SmallWord = word1;
}
//Count and Display the like characters.
for (int i = 0; i < SmallWord.length(); i++)
{
if (BigWord.contains(String.valueOf(SmallWord.charAt(i))))
{
System.out.println("both words contain the letter " + SmallWord.charAt(i));
count++;
}
}
//Display the count of like characters.
System.out.print("Number of like characters >> " + count);
}
}
Let's say you have word1 and word2:
String biggerWord;
String smallerWord;
if (word1.length() > word2.length()) {
biggerWord = word1;
smallerWord = word2;
} else {
biggerWord = word2;
smallerWord = word1;
}
for (int i = 0; i < smallerWord.length(); i++) {
if (biggerWord.contains(String.valueOf(smallerWord.charAt(i)))) {
counter++;
}
}
This figures out which word is bigger. Then for the length of smallerWord, iterate over it one character at a time and see if biggerWord contains that character. If it does, increment the counter.
counter should then have the number of common characters by the end of the loop.
This was written freehand, so be aware of syntax and minor logic errors. Or I misunderstood your assignment. It should be pretty close though.
A really nice way is to sort the string alphabetically.
sortedWord1 = new String(Arrays.sort(word1.toCharArray()));
sortedWord2 = new String(Arrays.sort(word2.toCharArray()));
What that does is turn the words into character arrays, sort them alphabetically, then makes them into a string again.
The next step is just to iterate from the beginning and print out all common characters. This would be easier since they're sorted.
int index1 = 0;
int index2 = 0;
while((index1 < sortedWord1.length()) && (index2 < sortedWord2.length()) {
if(sortedWord1.charAt(index1) == sortedWord2.charAt(index2)) {
System.out.print(sortedWord1.charAt(index1) + " ");
index1++; index2++;
}
else if(sortedWord1.charAt(index1)> sortedWord2.charAt(index2)) {
index2++;
}
else {
index1++;
}
}
I haven't checked it for syntax errors, but it should be good.