This is a assignment I'm doing and it seems I can't get it to work properly.
The question is below.
A palindrome is a word or phrase that reads the same forward and
backward, ignoring blanks and considering uppercase and lowercase
versions of the same letter to be equal.for example,the following are
palindromes:
warts n straw
radar
able was I ere I saw Elba
xyzczyx
Write a program that will accept a sequence of characters terminated
by a period and will decide whether the string--without the
period---is a palindrome.You may assume that the input contains only
letters and blanks and is at most 80 characters long.Include a loop
that allows the user to check additional strings until she or he
requests that the program end.
Hint: Define a static method called isPalindrome that begins as
follows:
Precondition: The array a contains letters and blanks in
positions a[0] through a[used - 1]. Returns true if the string is a
palindrome and false otherwise.
public static boolean isPalindrome(char[] a, int used)
Your program should read the input characters into an array whose base
type is char and then call the preceding method. The int variable used
keeps track of how much of the array is used, as described in the
section entitled "Partially Filled Arrays."
This is my class code:
public class Palindrome_class
{
// instance variable
char[] characterArray;
//constructor
//#param data is a string of characters
public Palindrome_class(String data)
{
characterArray = data.toUpperCase().toCharArray();
}
//#return true if the word is a palindrome, otherwise returns false.
public boolean isPalindrome(char[] a, int used)
{
int i = 0, j = used - 1;
while (i < j)
{
if(characterArray[i] == characterArray[j])
{
i++;
j--;
}
else
{
return false;
}
}
return true;
}
}
This is my main code:
import java.util.Scanner;
public class palindromeTest
{
public static void main(String[] args)
{
int used = 0;
char[] chars = new char[80];
Scanner inputWord = new Scanner(System.in);
Scanner reply = new Scanner(System.in);
System.out.println("Enter a string characters, terminated by a period.");
String data;
String cq;
Palindrome_class word;
do
{
//input word from user.
data = inputWord.nextLine();
word = new Palindrome_class(data);
//check for palindrome.
if(word.isPalindrome(chars, used))
System.out.println(data + " is a palindrome.");
else
System.out.println(data + " is not a palindrome.");
//request to continue or quit.
System.out.println("Continue or Quit?");
cq = reply.nextLine();
}
while (cq.equalsIgnoreCase("continue"));
System.exit(0);
}
}
This is the results:
Enter a string characters, terminated by a period.
radar.
radar. is a palindrome.
Continue or Quit?
continue
use
use is a palindrome.
Continue or Quit?
continue
use.
use. is a palindrome.
Continue or Quit?
continue
apple.
apple. is a palindrome.
Continue or Quit?
Quit
Please tell me where I'm making a mistake.
You are checking whether a String is a palindrome with this call :
if(word.isPalindrome(chars, used))
However, used is 0, so your method always returns true.
You are also ignoring the instructions of your assignment. You are not doing anything with the chars array, you are not removing the period that's supposed to be at the end of the input String, your isPalindrome method is not static, etc...
U did a very little mistake.. U are sending "used" variable as 0 each time. ideally it should be length of a word.
please check it. use
used = data.length();
before sending it to the check method
Related
I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.
This code focuses on strings, decision making [ if statements ], and parameter passing.
So far I have a runner class and the return method to use for the vowel:
public class FirstLastVowel {
public static String isVowel(String letter) {
String fl = letter.substring(0, 1);
String LL = letter.substring(letter.length() - 1);
String vowel = "AEIOUaeiou";
vowel.indexOf(letter);
if(
}
}
import java.util.*;
import java.io.*;
public class StringRunner_Cavazos {
public static void main(String[] args) throws IOException {
Scanner fileIn = new Scanner(new File("firstLastVowel.dat"));
while(fileIn.hasNext()){
System.out.println(FirstLastVowel.isVowel(fileIn.nextLine()));
}
}
}
In the FirstLastVowel.java I have to put the substrings into variables and compare them to the indexOf(vowel) which is AEIOUaeiou and I'm stumped on what to type.
Edit #1: So I have changed some of the code, I removed the for loop and added 'vowel.indexOf(letter)' now how do I check the word if it's empty and return 'no' compared to if I can pull the first letter and the last letter and return 'yes'?
First, you do not need a loop: checking the initial letter is a one-time deal, you do not need to check letters beyond the initial one to determine if the word starts with a vowel or not.
You are on the right path with letter.indexOf(vowel) expression. However, you are ignoring the return value, which is why your code is not behaving the way you want. It should also be the other way around, i.e. vowel.indexOf(letter)
You need to check the result of the call to see if it is negative or non-negative. If the first letter is a vowel, the result is going to be non-negative; otherwise, the result is going to be negative.
The code should proceed as follows:
See if the word is empty, and return "no" if it is
Take the first letter of the word, and check if its index in the list of vowels is non-negative.
If the index is non-negative, return "yes"; otherwise, return "no".
I'm trying to create a program that parses through an input and determines whether or not it is a palindrome. Pasted below is my code so far:
import java.util.Scanner;
//Gets a message and shift amount and caesar shifts the message by the desired amount. Displays the enciphered message.
public class RobustPalChecker{
public static void main(String[] args){
//declare variables
char current, currentReverse;
int msgInt;
String msg, msgReverse;
StringBuffer sbMsg, newMsg;
Scanner sc = new Scanner(System.in);
//get message
System.out.println("Please enter an integer: ");
msg = sc.nextLine().toUpperCase();
//msgReverse = new StringBuffer(msg).reverse().toString();
System.out.println(msg);
//System.out.println("= " + msgReverse);
//get first and last index of string to check if it's a palindrome
for(int i = 0; i < msg.length(); i++) {
current = msg.charAt(i);
if(Character.isLetter(current) == false){
sbMsg = new StringBuffer(msg);
newMsg = sbMsg.deleteCharAt(i);
msgReverse = new StringBuffer(newMsg).reverse().toString();
}
}
if(newMsg.equals(msgReverse)) {
System.out.println("It's a palindrome");
}else {
System.out.println("It's not a palindrome");
}
}
}
Ignore comments as some of them don't apply and I have not cleaned it up yet. The line of code that I'm pretty sure is causing the error is the isLetter line. The goal of that loop is to find any character that is not a letter and just delete it, and that includes whitespace. That last if statement is the one that actually compares the reversed string and regular string. Now the output that the last if statement is giving me when I try to compile is "variable newMsg might not have been initialized" and the same for msgReverse, but that's not my main question.
My main question is: Is my logic here correct or incorrect?
Also, if you need me to rephrase the question, I can do that as I understand this might be hard to follow, I'm just panicking a little.
Your logic seems fine, but since code is not at all upto the mark its difficult to verify. I have written code in english commented format, if you are able to fill in the blanks all will fall in place.
Let's breakdown the problem in two sections :
Remove unwanted characters from string
Check if string returned from step1 is a pallindrome.
Create two functions :
String cleanUp(String arg){
//create a stringbuffer from arg
//start for loop
//delete unwanted chars from stringbuffer
//end loop
//make string from stringbuffer and return
}
boolean pallindrome(String arg){
//create a new string from arg reverse
//return true if reversed string and arg are same
}
Now call these functions from your main method.
I am trying to get my code to prevent a user input from having a number in it.
Essentially I want the code to do as follows:
ask for input
receive input
test whether or not the input contains a number(ex: 5matt vs matt)
if contains a number I want to System.out.println("Error: please do not input a number");
Heres the kicker (and why it's not a duplicate question): I can't use loops or other statements we haven't learned yet. So far the only true statements we've learned are if/else/else if statements. That means I can not use for loops, like some of the answers are suggesting. While they're great answers, and work, I'll lose points for using them.
System.out.println("Please input the first name: ");
String name1 = in.next();
System.out.println("Please input the second name: ");
String name2 = in.next();
System.out.println("Please input the third name: ");
String name3 = in.next();
name1 = name1.substring(0,1).toUpperCase() + name1.substring(1).toLowerCase();
name2 = name2.substring(0,1).toUpperCase() + name2.substring(1).toLowerCase();
name3 = name3.substring(0,1).toUpperCase() + name3.substring(1).toLowerCase();
I have this already but I can't figure out how to test if the input only contains letters.
Okay, there are many ways to deal with this. A good thing would be to use Regex (text matching stuff). But it seems that you should only use very basic comparison methods.
So, let's do something very basic and easy to understand: We iterate over every character of the input and check whether it's a digit or not.
String input = ...
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
System.out.println("Do not use digits!");
}
}
This code is very straightforward. But it will continue checking even if a digit was found. You can prevent this using a helper-method and then returning from it:
public boolean containsDigit(String text) {
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
return true;
}
}
// Iterated through the text, no digit found
return false;
}
And in your main program you call it this way:
String input = ...
if (containsDigit(input)) {
System.out.println("Do not use digits!");
}
Use a regular expression to filter the input
Eg
str.matches(".*\\d.*")
See this link for more info
There are several ways you could do this, among others:
Iterate over all the chars in the string and check whether any of them is a digit.
Check whether the string contains the number 1, number 2, number 3, etc.
Use a regular expression to check if the string contains a digit.
(Java Regular Expressions)
If you're allowed to define functions, you can essentially use recursion to act as a loop. Probably not what your prof is going for, but you could be just inside the requirements depending on how they're worded.
public static boolean stringHasDigit(String s) {
if (s == null) return false; //null contains no chars
else return stringHasDigit(s, 0);
}
private static boolean stringHasDigit(String s, int index) {
if (index >= s.length()) return false; //reached end of string without finding digit
else if (Character.isDigit(s.charAt(index))) return true; //Found digit
else return stringHasDigit(s, index+1);
}
Only uses if/elseif/else, Character.isDigit, and String.charAt, but recursion might be off limits as well.
So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.