Palindrome coding - java

I am trying to create a Palindrome tester in java using a method.. This is what I have so far. It is so close I just can't figure out why it won't say that it IS a palindrome and reverse it.
System.out.println("Fun with Palindromes!!");
Scanner in = new Scanner(System.in);
System.out.println("Enter the potential palindrome (or enter exit to quit): ");
String x = in.nextLine();
while(!x.equals("exit"))
{
String t = x.toLowerCase();
String u = CleanUpString(t);
Boolean wordCheck = checkPalindrome(u);
int wordCount = x.length();
String rev = "";
for(int i = 0; i <x.length(); i++)
{
rev = x.charAt(i)+rev;
}
if(wordCheck == true)
{
System.out.println("The orginal string\"" + u + "\" contains" + wordCount + "characters." );
System.out.println("The converted string\"" + rev + "\"is a palindrome");
}
else if(wordCheck == false)
{
System.out.println("The string \"" + u + "\" contains " + wordCount + " characters");
System.out.println("\"" + rev + "\" is not a palindrome");
}
System.out.println("\nEnter the potential palindrome, or enter exit to quit: ");
x = in.nextLine();
}
}
public static String CleanUpString(String words)
{
words = words.replace(".","");
words = words.replace("," ,"");
words = words.replace(":","");
words = words.replace("!","");
return words;
}
public static boolean checkPalindrome(String baseball)
{
String rev = "";
for(int i = 0; i<baseball.length()-1; i++)
{
rev = baseball.charAt(i) + rev;
}
if(rev.equals(baseball))
return true;
else
return false;
}
}

Here is the code I used to determine whether a string is Palindrome String or not:
private static boolean checkPalindrome(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0;i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}
For reversing strings, you can simply use:
String reverse = new StringBuffer(string).reverse().toString();
Hope these can help you.

Use StringUtils for this
import org.apache.commons.lang.StringUtils;
boolean isPalindrome(String word) {
return StringUtils.reverse(word).equals(word);
}

Here is another option
public class PalindromeTester {
public static void main(String[] args) {
try {
String s = args[0];
int i = args[0].length()-1;
int i2 = args[0].length();
char [] chrs = new char[i2];
for ( int i3 = i; i3 > -1; i3-- ) {
chrs[i2-i3-1] = (s.charAt(i3) );
}
String s2 = String.valueOf(chrs);
if ( s2.equals(s) ) {
System.out.println( s + " is a palindrome!");
} else {
System.out.println( s + " is not a palindrome");
}
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("Please enter at least one letter or digit!");
}
}
}

Here's how I did it:
public class palindromeTWO
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int right = 0;
int left = 1;
System.out.println("Please enter a word: ");
String word = scan.next();
int word_length = word.length();
while(word.charAt(right) == word.charAt(word_length - left) && left < (word_length / 2))
{
left++;
right++;
}
if(word.charAt(right) == word.charAt(word_length - left))
{
System.out.println("'" + word + "'" + " is a palindrome!");
}
else
{
System.out.println("'" + word + "'" + " is NOT a palindrome.");
}
}
}

1st implementation using recursion -
import java.util.ArrayList;
import java.util.stream.Collectors;
public class PalindromeManager {
private static String str = "ehcache";
private static ArrayList<String> list = new ArrayList<>();
public static void main(String[] args) {
test(str);
String output = list.stream().collect(Collectors.joining());
System.out.println(output);
if (output.equals(str)) {
System.out.println("it was palindrome");
} else {
System.out.println("Nope! it wasn't");
}
}
private static void test(String str) {
if (str.length() <= 0) {
return;
}
String lastChar = "" + str.charAt(str.length() - 1);
list.add(lastChar);
test(str.substring(0, str.length() - 1));
}
}
2nd implementation using iteration -
public class PalindromeManager2 {
private static String str = "ehcache";
public static void main(String[] args) {
int startIndex = 0;
int lastIndex = str.length() - 1;
boolean result = true;
while (true) {
if (startIndex >= lastIndex) {
break;
}
char first = str.charAt(startIndex);
char last = str.charAt(lastIndex);
/*if (first == ' ') {
startIndex++;
continue;
}
if (last == ' ') {
lastIndex--;
continue;
}*/
if (first != last) {
result = false;
break;
}
startIndex++;
lastIndex--;
}
if (result) {
System.out.println("Yes! It was");
} else {
System.out.println("Nope! it wasn't");
}
}
}

In checkPalindrome method change the condition of for loop from i<baseball.length()-1 to i<baseball.length().

Related

Using variables form other classes in java

I am trying to use two int variables from other classes in another class and then add them together into another variable and print the result. When I try this though, I always get a result of zero like the values are not being brought over into the new class and I can't figure out what the problem is.
Here is some example code:
class1
public static int finished = (match2.totalpoints + match3.iq);
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
EDIT: class2
public class match2 {
public static int totalpoints;
int a;
int b;
int c;
int d;
int e;
int f;
String guess;
String group;
String countdown[] = {
"3...",
"2...",
"1...",
""
};
String memorize[] = {
""
};
public match2() throws InterruptedException
{
int x = set2();
int y = set3();
int z = set4();
total(x, y, z);
System.out.println("For the next part of your IQ ASSesment\njust type back the words in CAPSLOCK in CAPSLOCK");
System.out.println("");
match3 n = new match3();
}
public void set1() throws InterruptedException
{
//Scanner s = new Scanner(System.in);
for (int i = 0; i < countdown.length; i++)
{
Thread.sleep(750);
System.out.println(countdown[i]);
}
}
public int set2() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
group = "" + a + b + c + d;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(guess.equals(group))
{
System.out.println("nice +1 bruh");
rv = 1;
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set3() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your next set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("good");
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set4() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your final set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
e = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f + e;
System.out.println(group);
System.out.println("");
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("great");
}
else if(!group.equals(guess))
{
System.out.println("eeeh buzer sound");
}
return rv;
}
public int total(int x, int y, int z)
{
System.out.println("");
int totalpoints = (x + y + z);
if(totalpoints == 3)
{
System.out.println("YOU GOT THEM ALL");
}
if(totalpoints <= 2 && totalpoints >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalpoints));
}
if(totalpoints == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
return totalpoints;
}
}
EDIT: class3
public class match3 {
public static int iq;
String countupdown [] = {
"READY...",
"SET.....",
""
};
String memorize [] = {
""
};
public match3() throws InterruptedException
{
int mem1 = memory1();
int mem2 = memory2();
int mem3 = memory3();
totalMemory(mem1, mem2, mem3);
}
public void methodCountdown() throws InterruptedException
{
for(int i = 0; i < countupdown.length; i++)
{
Thread.sleep(1000);
System.out.println(countupdown[i]);
}
}
public int memory1() throws InterruptedException
{
int rv = 1;
Scanner s = new Scanner(System.in);
System.out.println("Press ENTER when ready");
s.nextLine();
methodCountdown();
String a = word1();
String b = word2();
System.out.println("The " + a + " ate the " + b);
String wordgroup = "" + a + " " + b;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory2() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String c = word3();
System.out.println("The " + a + " drove the " + c);
String wordgroup = "" + a + " " + c;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory3() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String d = word4();
System.out.println("The " + a + " visited the " + d);
String wordgroup = "" + a + " " + d;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public static String word1()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "DOG";
}
else if(cv == 2)
{
word = "CAT";
}
else if(cv == 3)
{
word = "BIRD";
}
return word;
}
public static String word2()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "FOOD";
}
else if(cv == 2)
{
word = "MUD";
}
else if(cv == 3)
{
word = "GRAINS";
}
return word;
}
public static String word3()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "TRAM";
}
else if(cv == 2)
{
word = "BUS";
}
else if(cv == 3)
{
word = "BICYCLE";
}
return word;
}
public static String word4()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "MALL";
}
else if(cv == 2)
{
word = "PARK";
}
else if(cv == 3)
{
word = "POOL";
}
return word;
}
public void totalMemory(int mem1, int mem2, int mem3)
{
int iq = (mem1 + mem2 + mem3);
System.out.println("");
if(iq == 3)
{
System.out.println("YOU GOT THEM ALL");
}
else if(iq <= 2 || iq >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
}
else if(iq == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
}
}
total points is a variable from match2 class and iq from match3 class. Any help with any methods I could use to make this happen would be much appreciated. Thank You
Well ... besides the fact you are not following any code convention, Like class names should start with a capital letter and public static final fields (like totalpoints and iq) should be all Uppercase (code conventions, you are not sharring match2 and match3 codes, without it we can't understand what is happening inside those classes.
But you can do a simple test and assign a value to match2.totalpoints and match3.iq and you are going to see the summing of these two values being printed by the last system.out you put.
good luck and good Java studies!
Are the int variables you're trying to use inside child classes of your main parent class? Did you extend the child classes in your main parent class?
Class #1:
public int firstVar(int someNum) {
//code here
return someNum;
}
Class #2:
public int secondVar(int otherNum) {
//code here
return otherNum;
}
Class #3 Class with Main Method -
public class mainClass extends class#1; //etc
//code here and finally print out the finished number
You could try extending one of the classes that has an int you need into another one of the classes with the other int you need and then just extending that second class into your main, OR you could try completely redefining your classes and just placing all the ints you need into one separate class and then extending that single one into your main.
So I finally got it to work. The problem, I guess, was that I was trying to add together the variables from the other classes(match2 and match3) outside the main function within the class(match1) I was trying to add them together. All I did was move the expression adding the variables together from the top to inside the main function like this:
public static int finished;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
finished = (match2.totalpoints + match3.iq);
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
Thanks for all the help from everyone.
Smth. like this. You have lot's of code duplication
public class MatchRunner {
public static void main(String... args) throws InterruptedException {
new MatchRunner().start();
}
public void start() throws InterruptedException {
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println();
System.out.println("When taking the quiztest you have only two seconds before making each guess");
int totalPoints = new Match2().getTotalPoints();
System.out.println("For the next part of your IQ Assesment");
System.out.println("just type back the words in CAPSLOCK in CAPSLOCK");
int iq = new Match3().getIQ();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + (totalPoints + iq) + " POINTS");
}
}
public class Match2 {
public int getTotalPoints() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
int totalPoints = calc(scan, "first", "nice +1 try", "almost");
totalPoints += calc(scan, "next", "good", "almost");
totalPoints += calc(scan, "final", "great", "eeeh buzer sound");
printTotalPoints(totalPoints);
return totalPoints;
}
}
private static void countdown() throws InterruptedException {
for (int i = 5; i > 0; i--) {
Thread.sleep(750);
System.out.println(i + "...");
}
}
private static int calc(Scanner scan, String strSet, String strEqual, String strNotEqual) throws InterruptedException {
System.out.println("press ENTER for your " + strSet + " set...");
Random random = new Random();
scan.nextLine();
countdown();
int sum = 0;
for (int i = 0; i < 4; i++)
sum += random.nextInt(9) + 1;
System.out.println(sum);
for (int i = 0; i < 10; i++)
System.out.println();
int guess = scan.nextInt();
System.out.println(guess == sum ? strEqual : strNotEqual);
return guess == sum ? 1 : 0;
}
private static void printTotalPoints(int totalPoints) {
System.out.println();
if (totalPoints == 3)
System.out.println("YOU GOT THEM ALL");
else if (totalPoints <= 2 && totalPoints >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalPoints));
else if (totalPoints == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}
public class Match3 {
public int getIQ() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
Random random = new Random();
Supplier<String> getWord1 = () -> getWord(random, "DOG", "CAT", "BIRD");
Supplier<String> getWord2 = () -> getWord(random, "FOOD", "MUD", "GRAINS");
Supplier<String> getWord3 = () -> getWord(random, "TRAM", "BUS", "BICYCLE");
Supplier<String> getWord4 = () -> getWord(random, "MALL", "PARK", "POOL");
int iq = calc(scan, getWord1, getWord2, "ate the");
iq += calc(scan, getWord1, getWord3, "drove the");
iq += calc(scan, getWord1, getWord4, "visited the");
printIq(iq);
return iq;
}
}
private static void countdown() throws InterruptedException {
System.out.println("READY...");
Thread.sleep(1000);
System.out.println("SET...");
Thread.sleep(1000);
}
public int calc(Scanner scan, Supplier<String> wordOne, Supplier<String> wordTwo, String strMsq) throws InterruptedException {
System.out.println("Press ENTER when ready");
scan.nextLine();
countdown();
String a = wordOne.get();
String b = wordTwo.get();
System.out.println("The " + a + ' ' + strMsq + ' ' + b);
String wordGroup = a + ' ' + b;
for (int i = 0; i <= 10; i++)
System.out.println();
String wordGuess = scan.nextLine();
System.out.println(wordGroup.equals(wordGuess) ? "awesome cock muncher a match" : "nope");
return wordGroup.equals(wordGuess) ? 1 : 0;
}
private static String getWord(Random random, String one, String two, String three) {
int cv = random.nextInt(3) + 1;
if (cv == 1)
return one;
if (cv == 2)
return two;
if (cv == 3)
return three;
return "";
}
public void printIq(int iq) {
System.out.println();
if (iq == 3)
System.out.println("YOU GOT THEM ALL");
else if (iq <= 2 || iq >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
else if (iq == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}

Guessing letter without having to capitalize input

I am new to this and I am having hard time with this code. I made a hangman game but I am having issues with the words that have a capital letter. If I don't input a capital letter the letter will not appear.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Hangman {
static ArrayList<String> words = new ArrayList<>();
static boolean isCorrect;
private static Scanner input;
private static Scanner input2;
public static void main(String[] args) {
File filename = new File("hangman.txt");
if (!filename.exists()) {
System.out.println(filename.getAbsolutePath());
System.out.println(filename + " does not exist.");
System.exit(1);
}
try {
input2 = new Scanner(filename);
while (input2.hasNext()) {
words.add(input2.next());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
input2.close();
input = new Scanner(System.in);
String playStarts = "y";
int wins = 0;
int loses = 0;
final int MAX_GUESSES = 11;
List<String> usedWords = new ArrayList<>();
while (playStarts.equals("y")) {
String word = getWord();
usedWords.add(word);
String secretWord = getSecretWord(word);
int missCount = 0;
while (!word.equals(secretWord)) {
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().charAt(0);
if (!isAlreadyInWord(secretWord, ch)) {
secretWord = getGuess(word, secretWord, ch);
if (!isCorrect) {
System.out.print(ch + " is not in the word.");
missCount++;
System.out.println(" You missed "+ missCount + " times");
}
} else {
System.out.println(ch + " is already in word.");
}
if (missCount == MAX_GUESSES) {
System.out.println("You reached max number of guesses.");break;
}
}
if (missCount == MAX_GUESSES) {
loses++;
} else {
wins++;
}
System.out.println("The word is " + word + ". You missed " + missCount + " times");
System.out.println("Do you want to guess another word? Enter y or n >");
playStarts = input.next();
}
System.out.println("Number of wins is " + wins + ".");
System.out.println("Number of loses is " + loses + ".");
System.out.println("Used words:");
for (String word : usedWords) {
System.out.println(word);
}
input.close();
}
public static String getWord() {
return words.get((int) (Math.random() * words.size()));
}
public static String getSecretWord(String word) {
String hidden = "";
for (int i = 0; i < word.length(); i++) {
hidden += "*";
}
return hidden;
}
static public String getGuess(String word, String secretWord, char ch) {
isCorrect = false;
StringBuilder s = new StringBuilder(secretWord);
for (int i = 0; i < word.length(); i++) {
//I think the issue is in this section of the code:
if (ch == word.charAt(i) && s.charAt(i) == '*') {
isCorrect = true;
s = s.deleteCharAt(i);
s = s.insert(i, ch);
}
}
return s.toString();
}
public static boolean isAlreadyInWord(String secretWord, char ch) {
for (int i = 0; i < secretWord.length(); i++) {
if (ch == secretWord.charAt(i)) {
return true;
}
}
return false;
}
}
The code works fine but I just have an issue with the capitalization.
If your speculation be correct, the comparing the lowercase of both sides of the equation should fix the problem:
if (Character.toLowerCase(ch) == Character.toLowerCase(secretWord.charAt(i)) {
return true;
}
Better yet, you can lowercase the user character input when it actually happens:
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().toLowerCase().charAt(0);
There are some handy functions in the Character class that you can use (Character.toUpperCase() and toLowerCase()) that can help you compare whether the characters match.
if (Character.toLowerCase(ch) == Character.toLowerCase(word.charAt(i)) && s.charAt(i) == '*') will always be checking two lowercase letters, so the case of neither ch or word.charAt(i) will matter.

Loop issue with use of if statement

I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)

how to find common suffix in java by using method

How to find common suffix in java by using method
public static String commonSuffix (String s1, String s2)
I can't return the result in method. Please help me
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
//HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1="";
String reverse2="";
System.out.println("Please enter the first string: ");
String s1=input.nextLine();
System.out.println("Please enter the second string: ");
String s2=input.nextLine();
int l1=reverse1.length();
int l2=reverse2.length();
for ( int i = s1.length() - 1 ; i >= 0 ; i-- )
{
reverse1 = reverse1 + s1.charAt(i);
}
for ( int i = s2.length() - 1 ; i >= 0 ; i-- )
{
reverse2 = reverse2 + s2.charAt(i);
}
if(l1<l2){
int l3=l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
else {
int l3=l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
}
public static String commonSuffix (String reverse1, String reverse2,int l3){
String suffixies="";
for(int k=0; k<=l3 ; k++){
if(reverse1.charAt(k)!=reverse2.charAt(k)){
}
else{
suffixies+=reverse1.charAt(k);
}
}
return suffixies;
}
}
Can someone help me fix this code??
Your issue is that you return inside of the for loop. You should return after the for loop terminates.
Please see the following code (I have tested it):
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
// HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1 = "";
String reverse2 = "";
System.out.println("Please enter the first string: ");
String s1 = input.nextLine();
System.out.println("Please enter the second string: ");
String s2 = input.nextLine();
for (int i = s1.length() - 1; i >= 0; i--) {
reverse1 = reverse1 + s1.charAt(i);
}
for (int i = s2.length() - 1; i >= 0; i--) {
reverse2 = reverse2 + s2.charAt(i);
}
int l1 = reverse1.length();
int l2 = reverse2.length();
if (l1 < l2) {
int l3 = l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
} else {
int l3 = l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
}
}
public static String commonSuffix(String reverse1, String reverse2, int l3) {
String suffixies = "";
for (int k = 0; k < l3; k++) {
if (reverse1.charAt(k) != reverse2.charAt(k)) {
break;
} else {
suffixies += reverse1.charAt(k);
}
}
// Reverse again
String reverse = "";
for (int i = suffixies.length() - 1; i >= 0; i--) {
reverse = reverse + suffixies.charAt(i);
}
return reverse;
}
}
Output:
Please enter the first string:
caption
Please enter the second string:
action
noitpac noitca
tion
This could be the best
**
package com.tm;
import java.util.Scanner;
public class CommSuffix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str[] = scan.nextLine().split(",");
String commSufffix=null;
if(str[0].trim().length() > str[1].trim().length()) {
String temp = str[0].trim();
str[0] = str[1].trim();
str[1] = temp;
}
for(int i=0;i<str[0].length();i++) {
String subStr = str[0].substring(i,str[0].length());
if(str[1].endsWith(subStr)) {
commSufffix = subStr;
break;
}
}
System.out.println(commSufffix);
}
} **

How to return a string?

import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();

Categories