Replacing an Exclamation mark at the end of a string - java

I am writing a program that counts song lyrics. Right now I have it programmed to delete certain characters using line.replace, for example:
String computerComma=",";
String computerPeriod=".";
String nothing="";
line=line.replace(computerComma,nothing);
line=line.replace(computerPeriod,nothing);
and this works totally fine. However, when I try
String computerExclamation="!";
line=line.replace(computerExclamation,nothing);
it messes up my entire program and many of my word counters. Does anybody know the reason behind this?
Thanks!

No. Works fine.
public static void main(String[] args) {
String computerExclamation="!";
String line = "i am a String !!.";
line=line.replace(computerExclamation,"");
System.out.println(line); //i am a String .
}
Error lies some where else.
You can see here.

Related

How to find out which delimiter was last used by Scanner with multiple delimiters

Just skip to the question if you don't care about examples/backstories
Story behind this
I'm currently trying to debug a piece of code so that I can fix any problems so I won't have to rewrite the whole thing later. Unfortunately, it prints out an eyesore so I'm trying to clean it up
Examples
These examples already include the fix I tried, but I marked it out. Also, please note they're all canon with each other
The Main class (the one that prints out the debug info)
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(Foo.toString).useDelimiter("\\[|\\]|,]"); //I'm using the delimiters "[", "]", and ",", because they're used for the debug program to separate Objects/Arrays
//My fix starts here
String debugOutput = "Output: "
do{
try {
foo = s.next();
debugOutput = debugOutput + foo + "\n";
} catch (NoSuchElementException ignore){
bar = false;
}
} while (bar);
//My fix ends here
System.out.println(debugOutput); //Without a fix, the debugOutput would be debugInfo
}
}
The Foo class that I'm debugging
class Foo{ //Class I'm trying to debug
//The code I'm busy debugging (for a list of classes, see the output as I don't feel like typing it all out
#Override
public String toString() {return ToStringBuilder.reflectionToString(this);}
}
The output I'm getting without my "fix"
ExampleClass#123456[ExampleArray1=[ExampleString1="Example String 1",ExampleString2="Example String 2"],ExampleObject1#234567=[ExampleString3="Example String 3",ExampleString4="Example String 4"],ExampleString5="Example String 5"]
The output I'm looking for (doesn't have to be exactly the same)
ExampleClass#123456
ExampleArray1=
ExampleObject2="Example String1"
ExampleObject3="Example String2"
ExampleObject1#234567=
ExampleString3="Example String 3"
ExampleString4="Example String 4"
ExampleString5="Example String 5"
External libraries that I'm using
org.apache.commons.lang3.builder.ToStringBuilder
My question
Is there a way to find out what delimiter has last been used?
It doesn't have to be Scanner, and since this won't be in the final code, it doesn't matter how messy the solution is.
I realize this is a popular question to ask, but all the questions were looking for a more closed answer. I'm fine with changing a lot of what I've done so far.

New to Java -- Return Unit test failing

Im working on a Java program in class and im unsure why or how this is failing considering I get the correct print out when the program is ran.
Here is the code I have:
import java.util.Scanner;
public class TextAnalyzer {
// Create scanner
private static Scanner scnr = new Scanner(System.in);
// Create text string
private static String text;
public static void main(String[] args) {
System.out.println("Enter a sentence or phrase: ");
// Scan for text input
text = scnr.nextLine();
System.out.println("You entered: " + text);
// Call getNumOfCharacters
int count = getNumOfCharacters();
System.out.println();
System.out.println("Number of characters: " + count);
// Call outputWithoutWhitespace
String modifiedstring = outputWithoutWhitespace();
System.out.println("String with no whitespace: " + modifiedstring);
}
// Method outputs string without spaces
private static String outputWithoutWhitespace() {
text = text.trim().replaceAll(" ", "");
return text;
}
// Method to return number of characters
private static int getNumOfCharacters() {
return text.length();
}
}
The output passes on all levels, it's the Unit test for the number of characters in the input that is failing and I really just need some guidance as a new student to Java programming.
Here is a printout of the tests:
My assumption is that the getNumOfCharacters() is returning the number of characters AFTER the whitespaces have been removed, but I could be wrong.
Any help/guidance would be greatly appreciated.
Your assumption is correct and the problem is that you are replacing text with the stripped text:
private static String outputWithoutWhitespace() {
text = text.trim().replaceAll(" ", "");
return text;
}
... and now getNumOfCharacters() is returning the stripped length, which is no longer e.g. 46.
That is, when you hit this line in main:
String modifiedstring = outputWithoutWhitespace();
It has the side-effect of replacing text, since that's precisely what you told outputWithoutWhitespace() to do. So by the time main ends, text now contains the modified text, and subsequent calls to getNumOfCharacters() fail the unit tests.
Your printed output is misleading (still prints "46") because you compute and store the character count before you mess up text in outputWithoutWhitespace().
This is a good exercise in how to process and manage data, and a good learning experience for you. It's also a nice demonstration of the value of unit tests in quality control; you should remember this lesson.
Here's a hint: Based on your application requirements, does outputWithoutWhitespace() really need to store the trimmed text? Or does it just need to return it?
In the future, for debugging, consider:
Stepping through in a debugger where possible to examine what's happening along the way.
Adding diagnostic printouts, for example, print the value of text in getNumOfCharacters() to verify that it is what you think it is. Especially given your assumption that the problem was here and the failed unit test, this would be a good place to start investigating.

Cannot find symbol on dot?

I'm always having this error but error and I don't know how to fix it. Ok I will explain you.
I'm starting to learn code right now and when I write anything with dots(like System.out.printIn()) it gives me this error:cant find symbol. And it points the dot before printIn.
But its not on all dots, last code i write was:
public class Pryt {
public static void main(String[] args) {
String aString = "mynameisigna";
System.out.println(aString);
String reverse = new StringBuffer(aString).reverse().toString();
System.out.println(reverse);
System.out.println(**aString.lenght**);
}
}
And in this case it gives me the error on
System.out.println(aString.lenght);
The only solution I can take is to copy a example code from internet and I don't find this solution useful.
check your spelling - it's length, not lenght
it's a method, therefore aString.length()

Debugging variable error with Java

I am trying to do this stuff. If a user enters "C:\Windows\system32\foo.txt" then the program will convert it to "C:\\Windows\\system32\\foo.txt". A front slash needs to be added to every other preceding slash. Here's what I have coded till now (only the section relevant):
import javax.swing.*;
public class test {
public static void main(String[] args){
String path = JOptionPane.showInputDialog(null, "Enter the File path", "Word counter", JOptionPane.INFORMATION_MESSAGE);
for (int z=0;z<=path.length()-1;z++)
{
if (path.charAt(z) == '\\')
{
path.charAt(z) = "\\\\";
}
}
System.out.println(path); // For knowing what's going on
}
}
Unfortunately it's not compiling, and I don't have a clue of what to do. Any possible help welcomed. Thank you!
You are trying modify a String. Remember strings are immutable.
you can try something like
path.replace(oldChar, newChar) if you want to replace some chars.
This: path.charAt(z) cannot be on the left side of an assignment statement. Instead concatenate your String or use a StringBuilder.
Or just use String's replace(...) method.

Simple Recursion Issue Back ways

public class recursionExcercise4
{
public static void main (String[] args)
{
boolean statement=false;
String ch="";
String a="I am bubbles who is a little slugger and loves apple and yellow."
BacktoBacks(a,ch,statement);
}
public static void BacktoBacks(String sentence, String ch, boolean statement)
{
String newLine="",word="";
System.out.print(sentence.charAt(0));
if(sentence.charAt(0)=='.') System.out.println();
if(sentence.length()>1)
{
int num=sentence.substring(1).indexOf(" ");
word = sentence.substring(0,num);
System.out.println(word);
}
BacktoBacks(newLine,ch,statement);
}
}
That is the code.
The lines inside the if statement loop were added by me so you can change that but nothing else can be changed. The if statement on top must remain there. Also, I am trying to avoid loops as it makes it too easy then. Any way to do this? I tried it but need help.
The objective is to print out the words from the string that have double letters. This should also be printed backwards. So like this:
Yellow
Apple
Slugger
Little
Bubbles
Your help is much appreciated.
Thanks!!
So you need a function to check whether a word contains double letters,
public boolean hasDoubleLetters(String word){
// test
}
and based on its outcome, print the word after the recursive call. And you have to pass the correct argument to the recursive call.

Categories