Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm having a hard time learning java and I was hoping to get some type of help on doing this. I'm trying to get the user to input a word and have the system check to see if its a palindrome. I've taken some code from others to get some help but I'm getting stuck.
import java.util.Scanner;
class PalidromeTester
{
public static boolean isPalindrome (String[] word) {
for (int i=0; i< word.length; i++) {
if (!word[i].equals( word[word.length-1-i])){
return false;
}
}
return true;
// read word
public static String readWord(Scanner input){
String word = input.nextLine();
word = word.toLowerCase();
return word;
}
// display results to the screen
public static void displayResults(boolean result){
// display the results
String msg = "\nThat string ";
msg += (result == true) ? " IS " : " is NOT ";
msg += " a palindrome.\n";
System.out.println(msg);
}
// main function
public static void main(String[] args){
// input scanner
System.out.print('\u000C');
System.out.println("Enter the word: ");
Scanner input = new Scanner(System.in);
PalidromeTester.readWord(input);
}
}
Assuming your need, I think this is what you need. I have commented the changes done in the code itself to point out to you why the changes were done in the first place. Also remember there are multiple ways to approach a problem, this is merely just one of those possibilities. Feel free to innovate and add your own technique for solving this.
import java.util.Scanner;
public class Palindrome { //<-- added public to the class otherwise main method won't be called
public static boolean isPalindrome(String word) { //<--changed the String[] to String
for (int i = 0; i < word.length(); i++) {
if (!(word.charAt(i) == word.charAt(word.length() - 1 - i))) { //Since [] will not work on Strings, using charAt() to do the same thing
return false;
}
}
return true;
}
// read word
public static String readWord(Scanner input) {
String word = input.nextLine();
word = word.toLowerCase();
return word;
}
// display results to the screen
public static void displayResults(boolean result) {
// display the results
String msg = "\nThat string ";
msg += (result == true) ? " IS " : " is NOT ";
msg += " a palindrome.\n";
System.out.println(msg);
}
// main function
public static void main(String[] args) {
// input scanner
System.out.print('\u000C');
System.out.println("Enter the word: ");
String s = readWord(new Scanner(System.in)); //Added a call to the readWord method and also passed a Scanner reference to the method and
//storing the read word in String s
boolean result = isPalindrome(s); //Added a call to the palindrome method and also passing the read string s to the method to find whether
//it is palindrome or not and storing the method return value in boolean result variable
displayResults(result); //Finally calling the displayResults with the result we got from isPalindrome() to display the appropriate message
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I'm starting to code and trying to do a challenge of turning a sentence into camelCase. After some experimenting on my own, got to the following code:
package teste;
import java.util.Scanner;
public class Teste {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Insert the sentence to be turned into camelCase: ");
String entry = keyboard.nextLine();
System.out.print("Insert the character that is used as space: ");
String space = keyboard.nextLine();
char current;
char next;
String output = null;
for (int i=0; i<=entry.length(); i++){
current = entry.charAt(i);
next = entry.charAt(i+1);
if (i == entry.length()){
output += Character.toLowerCase(current);
} else if (entry.substring(i, i+1).equals(space)){
output += Character.toUpperCase(next);
i++;
} else {
output += Character.toLowerCase(current);
}
}
System.out.println("This sentence in camelCase is: " + output);
}
}
There is an error I can't seem to avoid with the last index of the input, even with the first if structure made especially for it, and I can't find out why. Could anyone explain to me what I did wrong?
you should avoid StringIndexOutOfBoundsException exception in line 15 "entry.charAt(i+1)",
This code will fix your error.
import java.util.Scanner;
public class Teste {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Insert the sentence to be turned into
camelCase: ");
String entry = keyboard.nextLine();
System.out.print("Insert the character that is used as
space: ");
String space = keyboard.nextLine();
char current;
char next;
String output = "";
for (int i=0; i<entry.length()-1; i++){
current = entry.charAt(i);
next = entry.charAt(i+1);
if (i == entry.length()-2){
output += Character.toLowerCase(current);
} else if (entry.substring(i, i+1).equals(space)){
output += Character.toUpperCase(next);
i++;
} else {
output += Character.toLowerCase(current);
}
}
//here we test the last character
int len=entry.length();
current = entry.charAt(len-1);
if(!entry.substring(len-1, len).equals(space)){
output += Character.toLowerCase(current);
}
System.out.println("This sentence in camelCase is: " +
output);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am taking an Java Introduction class and we have a project that deals with a hangman game. I have most of the all code worked out but there is a way to simplify the code.
In my code below, the program will output a message for every round (max 3 round) then using game.nextRound() it set will a word using variable named word1, word2, word3. This variable will be called in sequence in descending order.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
String word1 = "ruby";
String word2 = "python";
String word3 = "swift";
Scanner kb = new Scanner(System.in);
Hangman game = new Hangman();
System.out.println("Let's play a round of hangman.");
System.out.println("We are playing hangman");
game.nextRound(word1);
while (true) {
System.out.println("");
System.out.println("The disguised word is " + game.disguised());
System.out.println("Guess a letter:");
char guess = kb.next().charAt(0);
boolean isFound = game.guessLetter(guess);
if (isFound) {
game.result();
if (game.disguised().equals(game.secret())) {
game.found();
break;
}
} else {
game.result();
}
}
System.out.println("");
System.out.println("Let's play a second round of hangman.");
System.out.println("We are playing hangman");
game.nextRound(word2);
....
....
....
Hangman.java
public String disguised() {
return disguisedWord;
}
You can do the following :
-Put the Strings word1, word2, and word3 in an array of type String.
Let's say
String[] words = {"ruby", "python", "swift"};
-Initialize an int counter set to 0.
int c = 0;
-Add game.nextRound(words[c++]); inside your if and else statements in the while loop.
You can use ArrayList, and also use counter to indicate the number of the game.
public class Game {
public static void main(String[] args) {
int count = 1;
List<String> words = new ArrayList<>();
words.add("ruby");
words.add("python");
words.add("swift");
for (String word : words) {
System.out.println("Let's play a round of " + count + "hangman.");
System.out.println("We are playing hangman");
Hangman game = new Hangman();
game.nextRound(word);
while (true) {
System.out.println("");
System.out.println("The disguised word is " + game.disguised());
System.out.println("Guess a letter:");
char guess = kb.next().charAt(0);
boolean isFound = game.guessLetter(guess);
if (isFound) {
game.result();
if (game.disguised().equals(game.secret())) {
game.found();
break;
}
} else {
game.result();
}
}
count++;
}
}
}
I'm still fairly new to Java and understanding the basics of everything, we just started talking about methods.
I'm having a hard time implementing this new method.. without using arrays or vectors or anything in the sort..
Any help would be greatly appreciated!
public class ClosedLab07{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
String str = getInputString(keyboard);
int count = getWordCount(str);
System.out.println("Your string has " + (count+1) + " words in it.");
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(Scanner inScanner) {
String str = "";
while (str.equals("")){
System.out.print("Enter a string: ");
str = inScanner.nextLine();
if (str.equals("")){
System.out.println("ERROR - string must not be empty.");
System.out.println();
}
}
return str;
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
int i = 0;
int wordCount = 0;
while (i < input.length()){
char pos = input.charAt(i);
if (pos == ' '){
wordCount++;
}
i++;
}
return wordCount;
// Fill in the body
}
private static String getFirstWord(String input)
// THIS IS THE METHOD I'M WORKING ON
}
Add this line to your new method
return input.split("\\s")[0]; // split returns an array of all the words. you need just the first word
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have two approach to determine number of words in String, But the result is 1 forever!
public static void main(String[] args) {
System.out.println("Enter your String:");
String string = in.next();
System.out.println("Number of Words are:" + countWords(string));
System.out.println("Number of Words are:" + countWords2(string));
}
public static int countWords(String str) {
String[] splited2 = str.split(" ");
return splited2.length;
}
public static int countWords2(String str) {
String trimed = str.trim();
return trimed.split("\\s+").length;
}
Why?
Scanner#next() method, which is what I assume you are using, reads the next token, and by default it doesn't consider whitespaces as a part of token. So, it really reads the input till it finds the first whitespace.
So, your input contains just a single word, and hence the result. Try using Scanner#nextLine() method, and you will get the expected result.
Replace in.next() by scanner.nextLine() because next() will give you the next token not all the line
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:");
String sentence = scanner.nextLine();
System.out.println("Number of Words are:" + countWords(sentence));
Or you can use BufferedReader as it is faster in reading whole line
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String sentence = br.readLine();
System.out.println("Number of Words are:" + countWords(sentence));
I would suggest building a function like this:
public static int getWordCount(String string){
int counter = 0;
boolean wordFound = false;
int endOfLineIndex = s.length() - 1;
for (int i = 0; i < endOfLineIndex; i++) {
if (Character.isLetter(s.charAt(i)) == true)) {
wordFound = true;
} else if (Character.isLetter(string.charAt(i)) == false && wordFound == true) {
counter++;
wordFound = false;
} else if (Character.isLetter(string.charAt(i))) {
counter++;
}
}
return counter;
}
Hope I helped!
I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.