New to Java -- Return Unit test failing - java

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.

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.

absolute java textbook example error [closed]

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 years ago.
Improve this question
Can't figure out the small error I've made. This example is from the Absolute java textbook.
public class Display1_7 {
public static void main(String[] args) {
String sentence = "I hate text processing!";
int position = sentence.indexOf("hate");//finding the position of hate in variable sentence
String ending = sentence.substring(position = "hate".length());/*cuts out the first half
of the sentence*/
System.out.println("0123456789");
System.out.println(sentence);
System.out.println("The word \"hate\" starts at index "
+ position);/*example of using quotes inside a string,
also demonstrates concatenation of a variable*/
sentence = sentence.substring(0, position) + "adore"+ ending;//I think I did this wrong?
System.out.println("The changed string is:");
System.out.println(sentence);
}//end of main
}
The expected output is
The output I get is
You use an = instead of a + when you try to determine ending.
String ending = sentence.substring(position + "hate".length());
...should do the trick
The problem was that your String ending = sentence.substring(position ="hate".length()); should be String ending = sentence.substring(position +"hate".length());
Indeed, the ending is the position of hate (returned by IndexOf()) to which you add the length of the word that you want to remove (in this case "hate").
The assignment you had in your code actually changed the value of position which switched from 2 to 4 (the length of hate). Thus, not only was the ending string wrong but your position was also wrong, making the final String exactly what you had.
So here is a corrected (and working) version of your code
public class Display1_7 {
public static void main(String[] args) {
String sentence = "I hate text processing!";
int position = sentence.indexOf("hate");//finding the position of hate in variable sentence
String ending = sentence.substring(position +"hate".length());/*cuts out the first half
of the sentence*/
System.out.println("0123456789");
System.out.println(sentence);
System.out.println("The word \"hate\" starts at index "
+ position);/*example of using quotes inside a string,
also demonstrates concatenation of a variable*/
sentence = sentence.substring(0, position) + "adore"+ ending;
System.out.println("The changed string is:");
System.out.println(sentence);
}
}
Small note, I would avoid comments like "end of main", I mean there's just no point to them at all, anyone can understand that it was the end of main :). From what I gathered you're a beginner but still, this sort of comments just make useful comments fade away.

Get length of string method Java

I need to do this:
Create a program that asks for the user's name and says how many characters the name contains.
Your program should be structured so that you put the calculating of the name length in it's own method: public static int calculateCharacters(String text). The tests will be testing both the method calculateCharacters and the program overall.
I know how to count the characters in a string. I just can't figure out how to do this when I have to use a seperate method. Can someone please help me?
import java.util.Scanner;
public class LengthOfName {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type your name: ");
String name = reader.nextLine ();
int cal = calculateCharacters(name);
System.out.println(Number of characters: " + cal);
}
public static int calculateCharacters(String text) {
int cal = text.length ();
//System.out.println("Number of characters: " + count ());
return cal;`
What's the error? I'm not seeing any errors in logic here, just a couple syntax issues like missing a quotation mark around "Number of characters: ", a missing curly brace at the end of the calculateCharacters method, and an extra whitespace between reader.nextLine and ().
Your method call itself looks fine.

Does my method work for finding each word in a string

As the title suggests, I'm trying to make a method that will individually work on each word of a string. I've gotten the code down but I'm not sure if it is right. So I ran a couple of tests to see if it prints out appropriately. After multiple tries and absolutely nothing printing out. I need help. Can anyone find anything wrong my code?
public static String build( String str4, one test){
Scanner find = new Scanner( System.in);
String phrase = " ";
while ( find.hasNext()){
String word = find.next();
word = test.change(word);
phrase += word + " ";
}
return phrase;
}
The method change just changes the word to pig latin ( my intended goal ).
Here are the simple lines in my main method:
String str4 = "I am fluent in pig latin";
System.out.println (test.build(str4, test));
I intended for this code to print out this:
Iyay amyay uentflay inyay igPay atinLay
You attempt to get some input inside your function, using the Scanner instance, giving user input as its construction argument.
In order to print what is going to be returned, add this line:
System.out.println (phrase);
before your return statement.
What I am guessing though, is you are mistakenly using user input.
Try this instead:
public static String build( String str4, one test){
Scanner find = new Scanner(str4);
String phrase = " ";
while ( find.hasNext()){
String word = find.next();
word = test.change(word);
phrase += word + " ";
}
//Print your phrase here if you want.
System.out.println(phrase);
return phrase;
}
You have:
Scanner find = new Scanner( System.in);
Which means you're reading from user input.
You also have this str4 parameter, but you're not actually using it. You seem to have inadvertently used System.in as your input string source when you really meant to use your str4 parameter. Hence, nothing happens, as find.next() is waiting for input from the console rather than using the string you passed in.
You probably mean:
Scanner find = new Scanner(str4);

charAt method is returning an integer. Need to convert to int

I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.

Categories