Working with methods - java

I'm pretty new to coding Java. Below are codes for a program that is supposed to use several methods to ask for a string, reverse the string, test for palindrome and output the result of the test. I'm trying to debug my many errors.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original, String reverse) {
if (original.equals(getString(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String original, Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original,reverse);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
}
return reverse
}
public static void main(String[] args) {
System.out.print(promptForPalindrome);
}
}

For a start in main
you are calling
System.out.print(promptForPalindrome);
but if you look at the method promptForPalindrome you will see that it takes the parameters String original, Scanner Keyboard
BUT
These parameters are not even used, so maybe just delete them and change the main code to be
System.out.print(promptForPalindrome ());
Consider reading a basic java tutorial as well.
edit
Similar problems exist for isPalindrome - I suggest you change to
public static boolean isPalindrome(String original) {
return original.equals(getReverse(original));
}
and call it in as
boolean answer = isPalindrome(original);
But then your answer in
while (answer == false) {
will never change - so many bugs

The method signatures for the isPalindrome needs to be changed to only accept 1 string argument because you don't have the reversed string when it is called. Also there is no reason to pass in a scanner object for the prompt method because you instantiate it in the method. Also I changed your .equals to .equalsIgnoreCase so you don't get messed up by capitals. Also you need to update your boolean after each loop.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equalsIgnoreCase(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
answer = isPalindrome(original);
}
return getReverse(original);
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
Hope this helps I may have made some typos so let me know.

Your code has lot of errors. Check the below working code with comments in it.
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length() - 1; i > -1; i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) { // Two args are not required
// use equals if you need a case sensitive match
if (original.equalsIgnoreCase(getReverse(original))) { // Call getReverse() to reverse the string
return true;
} else {
return false;
}
}
public static String promptForPalindrome() { // Arguments are not required
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = null;
boolean answer = false;
do { // Use a do-while loop since you need to continue till it is success
original = keyboard.nextLine();
answer = isPalindrome(original);
if (!answer) {
System.out
.printf("Error: %s is not a palindrome. Please enter a palindrome.",
original);
}
} while (!answer);
keyboard.close(); // Close the Scanner
return original;
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
}

Thanks guys for all your help,
I was finally able to debug the code.
package osu.cse1223;
import java.util.Scanner;
public class Homework08a {
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equals(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String msg, Scanner keyboard) {
System.out.print(msg);
String userInput = keyboard.nextLine();
return userInput;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String msg ="Please enter a Palindrome";
String userInput = promptForPalindrome(msg, keyboard);
while (isPalindrome(userInput) == false) {
userInput = promptForPalindrome(msg, keyboard);
}
System.out.printf("%s is a palindrome", userInput);
}
}

Related

Changing and using one object array in two methods

I'm making a phone class and a phone book class right now. The phone class declares name and phone number fields, and the phone book class has read and run methods. When run() method is executed in the main function, information is input through the read() method, and information is retrieved and output through the run() method. However, I declared an instance array called phonebooks and tried to input the information received from the read() method into the array, but when I tried to output it through the run method, the array instances were not saved properly. There seems to be an issue where something isn't saving properly, how do I fix it?
import java.util.Scanner;
class Phone {
static private String name;
static private String tel;
public String getNum() {
return tel;
}
public String getName() {
return name;
}
public Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
}
public class PhoneBook {
private Scanner scanner;
static int repeat;
static Phone[] phonebooks;
public PhoneBook() {
scanner = new Scanner(System.in);
}
void read() {
System.out.print("Number of person to store? >> ");
int repeat = scanner.nextInt();
Phone[] phonebooks = new Phone[repeat];
for (int i = 0; i < repeat; i++) {
System.out.print("Name and Tel. No. >> ");
String name = scanner.next();
String tel = scanner.next();
phonebooks[i] = new Phone(name, tel);
if (i == repeat - 1) break;
}
System.out.println("Saved.");
}
void run() {
read();
while (true) {
System.out.print("Who do you wanna search for? >> ");
String search = scanner.next();
if (search.equals("stop")) break;
int i;
for (i = 0; i < repeat; i++) {
if (phonebooks[i].getName() == search)
System.out.println(search + "'s number is " + phonebooks[i].getNum());
break;
}
}
scanner.close();
}
public static void main(String[] args) {
new PhoneBook().run();
}
}
There are few issues in your code, below are some suggestions to make it work--
change member variables from static private to only private in Phone
Don't redeclare repeat & phonebooks in read().
Change if (phonebooks[i].getName() == search) call in run() to if (phonebooks[i].getName().equalsIgnoreCase(search)) so that it will search & match search string.

Java - Compare frequency of elements of a specific type

my task is to read a file and then print out the most 10 frequent words in the text file.
I have used the following comparator and it gives me correctly the first 3 most frequent words but then it kind of gets it all wrong and it only prints out 9 instead of 10.
Here is my comparator
import java.util.*;
class CompareFreq implements Comparator<HashElement>
{
public int compare(HashElement x, HashElement y)
{
if (y.getCounter() > x.getCounter())
{
return 1;
}
else
{
return -1;
}
}
}
And here is my main:
String[] temp = new String[100000];
Scanner obj = new Scanner(new File("file.txt"));
while (obj.hasNext())
{
String text = obj.nextLine();
for (String t : text.split(" "))
{
set.insert(t);
}
}
System.out.println("All words and the frequency:");
set.printTableInOrderAndFreq();
System.out.println();
System.out.println("Most 10 frequent words:");
set.getMaxWordsFrequency(10);
Here is the output that I am getting
Most 10 frequent words:
to
the
of
their
they
caused
with
companions
great
The first 3 (to, the, of) words are correct, they are the most frequent in my text but then the calculations are wrong. On top of that I believe it is deleting on of the 10 words where you can see there's a blank row between the word 'they' and 'caused'
I forgot to post my HashElement class, here it is
public class HashElement
{
private String word; // ordet
public int counter; // antalet förekomst av ordet
private boolean isActive; // behövs eventuellt för remove
public HashElement(String theword)
{
word = theword;
isActive = true;
}
public void increment()
{
counter++;
}
public int getCounter()
{
counter++;
return counter;
}
public String getWord()
{
return word;
}
public boolean getStatus()
{
return isActive;
}
public boolean changeStatus()
{
isActive = false;
return isActive;
}
}
Thanks for the help in advance

Validate if input is not numeric (number)

I am just a beginner. Am trying to validate if an input is numeric and not a string. I can't seem to get the correct result. It's always false.
import javax.swing.JOptionPane;
public class CheckDigit
{
public static void main(String[] args)
{
String containsOnlyNumbers;
containsOnlyNumbers = JOptionPane.showInputDialog("Please enter some numbers: ");
// System.out.println(containsOnlyNumbers("12345"));
// System.out.println(containsOnlyNumbers("12abc345"));
if (false)
{
JOptionPane.showMessageDialog(null, "False!");
}
else
{
JOptionPane.showMessageDialog(null, "True!");
}
}
public static boolean containsOnlyNumbers(String str)
{
for (int i = 0; i < str.length(); i++)
{
if (!Character.isDigit(str.charAt(i)))
return false;
}
return true;
}
}
Please advise. TIA.
If your want to use your solution you have to replace
if (false)
with
if (!containsOnlyNumbers(containsOnlyNumbers))
because you are not calling your method (same name for method and String).
You can also try like this,
public static boolean numericCheck(String str)
{
try{
double d=Double.parseDouble(str);
}catch(NumberFormatException e)
{
return false;
}
return true;
}
if method return true then input is a number, if return false input is not numeric

Java hangman help, my code included

**Hello, I have to create a hangman game in java. I cant use arrays. Most of my code is done but I have been having some problems and some tips would be welcome.
I just found something else that I could use help on. After prompting the user for a new secret word and using newHangMan.setSecretWord(newWord); my disguised word does not reset to "????" (with the same number of "?" as words in the secret word).
I'm very sorry for such a long post and the bad formatting(1st time posting here).
Can anyone help?**
This is my class file:
public class HangMan
{
private String secretWord = "bigbang", disguisedWord = "";
private int guessCount = 0, missCount = 0;
public void setSecretWord(String newWord)
{
secretWord = newWord;
guessCount = 0;
missCount = 0;
int wordLength = newWord.length();
while(wordLength > 0)
{
disguisedWord = disguisedWord + "?";
wordLength--;
}
}
public String getSecretWord()
{
return secretWord;
}
public boolean isFound()
{
return secretWord.equalsIgnoreCase(disguisedWord);
}
public String getDisguisedWord()
{
return disguisedWord;
}
public int getGuessCount()
{
return guessCount;
}
public int getMissesCount()
{
return missCount;
}
public void guessCharacter(char c)
{
// int position = secretWord.indexOf(c);
boolean got_it = false;
String updateDisguised="";
for(int i=0; i < secretWord.length();i++)
{
if(c == secretWord.charAt(i))
{
updateDisguised = updateDisguised + secretWord.charAt(i);
String checkDuplicate = updateDisguised.substring(0,i);
int duplicatePos = checkDuplicate.indexOf(c);
if(duplicatePos <0)
guessCount++;
got_it = true;
}
else
{
updateDisguised = updateDisguised + disguisedWord.charAt(i);
}
}
if(got_it == false)
{
missCount++;
guessCount++;
}
disguisedWord = updateDisguised;
}
}
This is my main method:
import java.util.Scanner;
public class HangManGame {
public static void main(String[] args)
{
boolean retry= true;
String retry_ans;
Scanner kb = new Scanner(System.in);
HangMan newHangMan = new HangMan();
String word = newHangMan.getSecretWord();
String input;
char guess;
newHangMan.setSecretWord(word);
System.out.println("Hangman game starts:");
do{
System.out.println("Guess this: " + newHangMan.getDisguisedWord());
System.out.println("Enter your guess character: [guess]");
input = kb.next();
guess = input.charAt(0);
newHangMan.guessCharacter(guess);
System.out.println(newHangMan.getDisguisedWord());
System.out.println("Number of guesses so far : " + newHangMan.getGuessCount());
System.out.println("NUmber of misses so far: " + newHangMan.getMissesCount());
if((newHangMan.getMissesCount()==7) || (newHangMan.isFound()))
{
System.out.println("The game is over");
System.out.println("Would you like to try again?");
retry_ans = kb.next();
if(retry_ans.equalsIgnoreCase("yes"))
{
retry = true;
System.out.println("Please enter a new secret word:");
String newWord = kb.next();
newHangMan.setSecretWord(newWord);
}
else
{
retry =false;
}
}
} while(retry == true);
}
}
(newHangMan.isFound()=true)
should be
newHangMan.isFound()
Do not make an bool compare to another bool.
The = is evaluate the boolean.
Replace
while(retry = true);
with
while(retry);
The former is an assignment, so it never evaluates to false although it should.
Your while condition is an assignment, rather than a comparison, which is likely the cause of your problem - you're setting the value of retry to true (retry = true) rather than checking that the value of retry currently equals true (retry == true).
Classic java starter error. while check stetement should be
While(retry == true)

Allowing a maximum number of times for system to accept incorrect PIN

I made a java login screen for a console application, but I need it to allow the user to input ther wrong PIN only 3 times. After the user has entered the PIN more than 3 times, the system should exit.
However, the loop which I used for the else part of the if condition does not seem to be making any changes to the program. (program wont execute the else part even once). Does anybody know what I am doing wrong?
if (userPIN.equals(a[0]))
{
System.out.println("You have login!");
valid=true;
String b=a[2];
Login.c=Double.parseDouble(b);
System.out.println(c);
obj.balance = Login.c;
obj.MainMenu();
System.exit(0);
}
else if(userPIN != a[0])
{
int count=0;
for(int i=0;i<count;i++)
{
System.out.println("Invalid PIN!");
check();
}
}
int count=0;
for(int i=0;i<count;i++)
The for loop's condition is initially false, hence it will never execute its body.
You have many problems in your code :
in the first if your using :
userPIN.equals(a[0])
but in the else you're using :
userPIN != a[0]
Your for loop cannot run correctly :
int count=0;
for(int i=0;i<count;i++)
Here is the correct implementation using Object-Orientation :
import java.util.Scanner;
public class PinChecker {
// Immutable Class
private static final class Pin {
private String _pin;
Pin(String pin) {
this._pin = pin;
}
public String toString() {
return _pin;
}
public boolean equals(Pin pin) {
if(pin.toString().equals(_pin)) {
return(true);
} else {
return(false);
}
}
}
public static final int NB_OF_TRIES = 3;
public static void main(String[] args) {
System.out.println("Enter your PIN :");
Pin userPin = new Pin("FOO");
Scanner console = new Scanner(System.in);
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
Pin keyedPin = new Pin(console.nextLine());
i++;
if(userPin.equals(keyedPin)) {
pinMatch = true;
} else {
System.out.println("Invalid PIN!");
}
}
if(pinMatch) {
System.out.println("OK, nb of tries :" + i);
} else {
System.out.println("KO, nb of tries :" + i);
}
}
}
You can store the keyedPin object if you need to.
in the else part try !(userPIN.equals(a[0]))
Your else part is not checking the contents.

Categories

Resources