I have a program in java that when you enter a sentence and the program tells you how many palindrome words there are and outputs the words. However, when I output the words I can't seem to get a comma after each output. For example if I input "Abba is running to the radar" It outputs that there's 2 palindromes and that the palindromes are "Abba radar". I however want it to output the palindromes as "Abba, Radar". No matter how I do it I can either get "Abba Radar" or "Abba, Radar". Any help would be appreciated.
The code
package strings;
import javax.swing.*;
public class Palindrome2 {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Words that are the same forwards and backwards are called palindromes.\nThis program determines if the words are palindromes.\n\nEnter a sentence(do not include a punctuation mark):");
String newWord[] = word.split(" ");
String palindromeWords = "";
int count = 0;
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
palindromeWords = palindromeWords + " " + newWord[i];
}
}
JOptionPane.showMessageDialog(null, "There are " + count + " palindromes in this sentence");
if (count != 0) {
JOptionPane.showMessageDialog(null, "The palindromes are:\n" + palindromeWords);
} else {
JOptionPane.showMessageDialog(null, "There isn't any palindromes.");
}
}
}
Just modify your code to:
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
palindromeWords = palindromeWords + newWord[i] + ",";
}
}
After the for loop, substring it to remove the last comma:
palindromeWords = palindromeWords.substring(0,palindromeWords.length()-1);
The code could also be
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
if (count > 1)
{
palindromeWords += ", ";
}
palindromeWords += newWord[i];
}
The comma goes before the new word after the first was found...
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Words that are the same forwards and backwards are called palindromes.\nThis program determines if the words are palindromes.\n\nEnter a sentence(do not include a punctuation mark):");
String newWord[] = word.split(" ");
StringBuffer palindromeWords = new StringBuffer();
int count = 0;
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
if (count > 0) {
palindromeWords.append(",");
}
palindromeWords.append(newWord[i]);
count++;
}
}
JOptionPane.showMessageDialog(null, "There are " + count + " palindromes in this sentence");
if (count != 0) {
JOptionPane.showMessageDialog(null, "The palindromes are:\n" + palindromeWords.toString());
} else {
JOptionPane.showMessageDialog(null, "There isn't any palindromes.");
}
}
So I altered palindromewords to be a StringBuffer and moved the count++ after the append operation. Hope this helps!
Related
So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}
I need some help with the code below.
What I'm trying to do is to write a program that reads in the file and computes the average grade and prints it out. I've tried several methods, like parsing the text file into parallel arrays, but I run into the problem of having the % character at the end of the grades. The program below is meant to add integers up too but the output is "No numbers found."
This is a clip of the text file (the whole file is 14 lines of similar input):
Arthur Albert,74%
Melissa Hay,72%
William Jones,85%
Rachel Lee,68%
Joshua Planner,75%
Jennifer Ranger,76%
This is what I have so far:
final static String filename = "filesrc.txt";
public static void main(String[] args) throws IOException {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(" ");
//For each word in the line
for(String str : words) {
try {
int num = Integer.parseInt(str);
total += num;
foundInts = true;
System.out.println("Found: " + num);
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total);
// close the scanner
scan.close();
}
}
Any help would be much appreciated!
Here's the fixed code. Instead of splitting the input using
" "
you should have split it using
","
That way when you parse the split strings you can use the substring method and parse the number portion of the input.
For example, given the string
Arthur Albert,74%
my code will split it into Arthur ALbert and 74%.
Then I can use the substring method and parse the first two characters of 74%, which will give me 74.
I wrote the code in a way so that it can handle any number between 0 and 999, and added comments when I made additions that you didn't already have. If you still have any questions however, don't be afraid to ask.
final static String filename = "filesrc.txt";
public static void main(String[] args) throws IOException {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
int successful = 0; // I did this to keep track of the number of times
//a grade is found so I can divide the sum by the number to get the average
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(",");
//For each word in the line
for(String str : words) {
System.out.println(str);
try {
int num = 0;
//Checks if a grade is between 0 and 9, inclusive
if(str.charAt(1) == '%') {
num = Integer.parseInt(str.substring(0,1));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is between 10 and 99, inclusive
else if(str.charAt(2) == '%') {
num = Integer.parseInt(str.substring(0,2));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is 100 or above, inclusive(obviously not above 999)
else if(str.charAt(3) == '%') {
num = Integer.parseInt(str.substring(0,3));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total/successful);
// close the scanner
scan.close();
}
Regex: ^(?<name>[^,]+),(?<score>[^%]+)
Details:
^ Asserts position at start of a line
(?<>) Named Capture Group
[^] Match a single character not present in the list
+ Matches between one and unlimited times
Java code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
final static String filename = "C:\\text.txt";
public static void main(String[] args) throws IOException
{
String text = new Scanner(new File(filename)).useDelimiter("\\A").next();
final Matcher matches = Pattern.compile("^(?<name>[^,]+),(?<score>[^%]+)").matcher(text);
int sum = 0;
int count = 0;
while (matches.find()) {
sum += Integer.parseInt(matches.group("score"));
count++;
}
System.out.println(String.format("Average: %s%%", sum / count));
}
Output:
Avarege: 74%
If you have a small number of lines that adhere to the format you specified, you can try this (IMO) nice functional solution:
double avg = Files.readAllLines(new File(filename).toPath())
.stream()
.map(s -> s.trim().split(",")[1]) // get the percentage
.map(s -> s.substring(0, s.length() - 1)) // strip off the '%' char at the end
.mapToInt(Integer::valueOf)
.average()
.orElseThrow(() -> new RuntimeException("Empty integer stream!"));
System.out.format("Average is %.2f", avg);
Your split method is wrong, and you didn't use any Pattern and Matcher to get the int values. Here's a working example:
private final static String filename = "marks.txt";
public static void main(String[] args) {
// Init an int to store the values.
int total = 0;
// try-for method!
try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
// Read line by line until there is no line to read.
String line = null;
while ((line = reader.readLine()) != null) {
// Get the numbers only uisng regex
int getNumber = Integer.parseInt(
line.replaceAll("[^0-9]", "").trim());
// Add up the total.
total += getNumber;
}
} catch (IOException e) {
System.out.println("File not found.");
e.printStackTrace();
}
// Print the total only, you know how to do the avg.
System.out.println(total);
}
You can change your code in the following way:
Matcher m;
int total = 0;
final String PATTERN = "(?<=,)\\d+(?=%)";
int count=0;
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
m = Pattern.compile(PATTERN).matcher(currentLine);
while(m.find())
{
int num = Integer.parseInt(m.group());
total += num;
count++;
}
}
System.out.println("Total: " + total);
if(count>0)
System.out.println("Average: " + total/count + "%");
For your input, the output is
Total: 450
Average: 75%
Explanations:
I am using the following regex (?<=,)\\d+(?=%)n to extract numbers between the , and the % characters from each line.
Regex usage: https://regex101.com/r/t4yLzG/1
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.
e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.
Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.
Thank you in advance for any help.
Jack
This is what I've got so far, but I don't think it works properly.
public class WordPlay {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word;
String palindrome = "";
String quit = "quit";
do {
System.out.print("Enter a word: ");
word = scanner.nextLine().toUpperCase();
int length = word.length();
for (int i = length - 1; i >= 0; i--) {
palindrome = palindrome + word.charAt(i);
}
if (word.equals(palindrome)) {
System.out.println("Is the word + palindrome + " same as " + word + "?", true);
} else {
System.out.println(false);
}
} while (!word.equals(quit));
System.out.println("Good Bye");
scanner.close();
}
}
Here it is.
public static void main(String[] args) {
// To take input.
Scanner scan = new Scanner(System.in);
System.out.print("Enter Word: ");
String word = scan.next(); // taking the word from user
// moving first letter to the end.
String newWord = word.substring(1) + word.charAt(0);
// reversing the newWord.
String reversed = new StringBuffer(newWord).reverse().toString();
// printing output.
System.out.println("You have entered '"+word+"'. "
+ "Is "+newWord+" same as "+word+"? "
+reversed.equals(word)+".");
// closing the input stream.
scan.close();
}
This works:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
char s2 = s1.charAt(0);
String s3 = s1.substring(1) + s2;
s3 = new StringBuilder(s3).reverse().toString();
if(s1.equals(s3))
System.out.println("They are same");
else
System.out.println("They are not the same");
}
}
This is very simple with some of observation. Your question is you have to move the first latter to the end and check reverse if the new string is same or not.
My ovservation:
For BANANA new string is ANANAB. Now reverse the string and check weather it is same as the first one.
Now If you ignore the first char B the string will be ANANA. As you have to reverse the string and check this one is same as the first one so this is like palindrome problem. For the input BANANA ANANA is palindrome. We are moving the first char to the end so there is no impact of it on checking palindrome. So I ignore the first char and check the rest is palindrome or not.
The Method is like:
private static boolean getAns(String word) {
int st = 1;
int en = word.length() - 1;
while (st < en) {
if (word.charAt(en) != word.charAt(st)) {
return false;
}
st++;
en--;
}
return true;
}
The main function is:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input your String:");
String word = scanner.nextLine();
boolean ans = getAns(word);
System.out.println("You have entered " + word + ". Is " + word.substring(1) + word.charAt(0) + " same as " + word + "? : " + ans + ".");
}
The Runtime for this problem is n/2 means O(n) and no extra memory and space needed,
I have tried to code it. See if it helps
import java.util.Scanner;
class StringCheck
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
String tempstr = new String();
System.out.println("Enter your String ");
str = sc.next();
int len = str.length();
//putting first character of str at last of tempstr
for (int i = 1 ; i<len; i++)
{
tempstr += str.charAt(i);
}
tempstr += str.charAt(0);
//reversing tempstr
char[] tempchar = tempstr.toCharArray();
int j = len-1;
char temp;
for ( int i = 0; i<len/2 ; i++)
{
if(i<j)
{
temp = tempchar[i];
tempchar[i] = tempchar[j];
tempchar[j]= temp;
j--;
}
else
break;
}
//reversing completed
tempstr = new String(tempchar);
// System.out.println("the reversed string is "+tempstr);
if(str.compareTo(tempstr)==0)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}
EDIT: Problem solved! I was just blind :)
As the title says, I've been working on finding the distance between two inputted words. The dictionary file is just a file with words separated by a space. Every time that I run the program, it says that I have 0 words between the two inputted. I'm not sure what I am doing wrong.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class wordDistance {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
Scanner sfile = new Scanner(new File("C:/Users/name/Desktop/Eclipse/APCS/src/dictionary.txt"));
int count = 0;
System.out.print("Type two words: ");
String start = s.next();
String end = s.next();
while (sfile.hasNextLine()) {
String line = sfile.nextLine();
String[] words = line.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i] == start) {
for (int j = i + 1; j < words.length; j++) {
if (!(words[j] == end)) {
count++;
}
if (words[j] == end) {
break;
}
}
}
}
}
System.out.println("There are " + count + " words between " + start + " and " + end);
}
}
the == operator checks whether the references to the objects are equal, use the method String.equals(String); instead.
For example:
if (words[j].equals(end))
if (!(words[j].equals(end)))
if (words[i].equals(start))
you should compare strings with equals() rather than ==
For example,
if (words[j].equals(end)) {
break;
}
if you change your comparisons you should get the correct output.
You cannot use the == operator to equate strings. Use the equals(String string) function instead.
if (!words[j].equals(end)) {
count++;
}
if (words[j].equals(end)) {
break;
}
"This is my code"
public static void main(String[] args) {
int letter_count = 0;
String check_word = new String ("How to equals a single character in string and then calculate it ");
String single_letter = " ";
int i = 0;
for ( i = 0; i < check_word.length(); i++ ) {
single_letter = check_word.substring(0);
if (single_letter.equals("a") ); {
letter_count ++;
}
}
System.out.println ( " - \"a\"" + " was found " + letter_count + " times");
}
You seem to be confused about what the substring function does. This line:
single_letter = check_word.substring(0);
essentially returns the whole of check_word and stores it inside of single_letter. I suspect what you actually wanted was this:
single_letter = check_word.substring(i, i + 1);
to get the single letter at that position.
You could also change it to:
if(check_word.charAt(i) == 'a') {
letter_count++;
}
One of your problems is that there is ; after your if (single_letter.equals("a") ) condition so your code
if (single_letter.equals("a") ); {
letter_count ++;
}
effectively is the same as
if (single_letter.equals("a") ){
//empty block "executed" conditionally
}
//block executed regardless of result in `if` condition
{
letter_count ++;
}
Other problem is that
single_letter = check_word.substring(0);
will get substring of check_word from index 0 which means that it will store same string as check_word. Consider using charAt method with i instead of 0. This will return simple char so you will need to compare it with == like check_word.charAt(i)=='a'.
Other (and probably better) approach would be just iterating over all characters of string with
for (char ch : check_word.toCharArray()){
//test value of ch
}
try...
public static void main(String[] args) {
int letter_count = 0;
char[] check_word = "How to equals a single character in string and then calculate it "
.toCharArray();
char single_letter = 'a';
for (int i = 0; i < check_word.length; i++) {
if (single_letter == check_word[i]) {
letter_count++;
}
}
System.out.println(" - \"a\"" + " was found " + letter_count + " times");
}
Why don't you use a character, like this:
public static void main(String[] args) {
int letter_count = 0;
String check_word = new String ("How to equals a single character in string and then calculate it ");
char toCheck = 'a';
for (int i = 0; i < check_word.length(); i++) {
char cursor = check_word.charAt(i);
if (cursor == toCheck) {
letter_count++;
}
}
System.out.println ( " - \"a\"" + " was found " + letter_count + " times");
}