Suppose I have this:
/**
* Single-word method.
*/
private void say(String word) {
System.out.println("Single word: " + word);
}
/**
* Multiple-word method.
*/
private void say(String... words) {
System.out.print("Multiple words: ");
for (String word : words) {
System.out.print(word);
}
System.out.println();
}
/**
* {#link #say(String...)}
*/
#SuppressWarnings("unused")
private void testJavadoc() {
}
public static void main(String[] args) {
say("hello");
say("world");
say("hello", "world");
}
If I run this, I get:
Single word: hello
Single word: world
Multiple words: helloworld
This proves that there is nothing wrong in defining a method with String and an overload with String....
When I mouse-over testJavadoc(), this is the Javadoc I see:
void testJavadoc()
#SuppressWarnings(value={"unused"})
say(String)
Clicking on say(String) brings me to the Javadoc for the first method without vararg.
If I remove say(String) method, then the Javadoc works fine.
I'm using eclipse neon 3 (4.6.3). Is this supposed to be the correct behavior?
This looks like it might be a bug in Eclipse, as you are correct in that it should reference the vararg method (I don't have Eclipse so I am unable to test).
Testing in IntelliJ, I can see the expected reference.
More-so, if you go ahead and actually generate the JavaDoc, you should be able to see the correct output.
Related
Hi I am hoping for a little direction/help on the following task I am struggling with..
Provide two classes which implement the ConsolePrint interface.
• One is called SimplePrint and it will just print the supplied argument directly to the console.
e.g. simplePrintObject.printInfo(“Heading this is not fancy”); would output:
Heading this is not fancy
• One is called FancyPrint. It should use StringTokenizer or String.split() to break up the string.
The first part of the string should be treated as a header and the other parts should be separated by tabs in the output.
e.g. fancyPrintObject.printInfo(“Heading this is quite fancy”); would output:
*********** Heading **********
this is quite fancy
******************************
Note: You should aim to have both “starred” rows take up the same width, regardless of the size of the header (for example, you can assume that the maximum length of the header string is 20 and that the first and last rows will output 30 characters – which will be 30 * in the case of the last row.)
Provide a basic class called ConsolePrintTest which will test each of the two classes. Make sure that your classes can handle empty strings and null strings.
So far I have written my interface as directed:
public interface ConsolePrint
{
void printInfo(String infoToPrint);
}
And a small program using the Split.split method..
public class PrintTester {
public static void main(String args[]) {
String str = new String("\n\n**************Heading************** \n\n\t" +
"This Is Quite Fancy\n" +
"\n***********************************");
for (String retval: str.split(" ", 1)) {
System.out.println(retval);
}
}
}
But trying to implement the ConsolePrint interface as directed in two classes has me stumped after days of reading and searching!
Read it literally: You have to write two classes.
public class SimplePrint implements ConsolePrint {
public void printInfo(String infoToPrint) {
// method implementation here
}
}
public class FancyPrint implements ConsolePrint {
public void printInfo(String infoToPrint) {
// method implementation here
}
}
and a test driver:
public class ConsolePrintTest {
public static void main(String [] args) {
ConsolePrint printer = null;
// figure out how to instantiate different types.
for (String arg : args) {
printer.printInfo(arg);
}
}
}
I have a problem in NetBeans with Command-Line Arguments, when run this code it says
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Note I put an argument in command line for NetBeans
public class NewEmpty1
{
public static void main(String arg[]){
System.out.println(arg[0]);
}
}
What is wrong ?
goto Project-Property-Run here you will see the option
main class
arguments
now make sure you are accessing the correct main class....after this option you have button to browse the class path. select it and then select the arguments finally you should be able to run the program...cheers!
Ashish
You have not passed any arguments..
And if you have passed arguments then it may be because you are invoking another class main method in the same package
the best way would be to iterate..
for(string s:arg)
System.out.println(s);
or
for(int i=0;i<arg.length();i++)
System.out.println(arg[i]);
subscript the string beyond its index is undefined.
this is your case. args[] is empty.
check this How to pass cmd line argument
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int argslen=args.length;
int argsValue[] = new int[argslen];
for (String i:args) {
int d = 0;
argsValue[d]=Integer.parseInt(i);
System.out.print(argsValue[d]+"\t"+"\n");
}
}
}
I was told in my class that I have to write and test my code in the main method, I wrote it, but I dont know how to test it. How I am supposed to test my methods? I am supposed to take user input, and then get the get the first letter, last letter, etc.
import java.util.Scanner;
public class Word
{
public static void main(String[] args)
{
}
public String word;
public void Word()
{
String word = "";
}
public void Word(String word1)
{
String word = word1;
}
public String getWord()
{
return word;
}
public void setWord(String newWord)
{
String word = newWord;
}
public void getFirstLetter()
{
String firstLetter = word.substring(0, 1);
}
public void getLastLetter()
{
String lastLetter = word.substring(word.length() - 1, word.length());
}
public void removeFirstLetter()
{
String noFirstLetter = word.substring(1, word.length());
}
public void removeLastLetter()
{
String noLastLetter = word.substring(0, word.length() - 1);
}
public int findLetter (String parameter)
{
word.indexOf(parameter);
return 1;
}
}
You test your methods by calling them with some defined input and compare the results with your expected output.
Example:
Suppose you have a method like this:
public static int add(int a, int b) {
return a + b;
}
You'd test it like this:
int result = add( 3, 5);
if( result != 8 ) {
//method is wrong
}
So basically you define a "contract" of what input the method gets and what the result should be (in terms of return value or other changed state). Then you check whether you get that result for your input and if so you can assume the method works correctly.
In order to be quite sure (you often can't be perfectly sure) you'd test the method several times with different types of input (as many as reasonable, to test different cases, e.g. short words, long words).
You often also test how your method handles wrong input, e.g. by passing null or empty strings.
You should have a look at tools like junit.
You can create a simple Test class and test your class and its behavior.
imports ...;
public class MyTest{
#Test
public void testMyClass(){
Word w= new Word();
w.setWord("test");
Assert.assertEquals(w.getFirstLetter(), "t");
}
}
With tools like Eclipse you could nicely run such a test.
Just a hint: you're very close you need an instance of Word, than you can call your methods
public static void main(String[] args) {
Word test = new Word();
test.setWord("something");
// here you might read javadoc of the String class on how to compare strings
}
EDIT:
I overlooked this:
public void setWord(String newWord)
{
String word = newWord;
}
The code you've written creates a variable word and newWord is assigned to it and then disappears.
If you (obviously) want to set a member of a class you should use this wich references the instance (you created in main()).
public void setWord(String newWord) {
this.word = newWord;
}
Since I would say this is homework, I will try not to explicitly give the answer. In the main method, you should set your word, then call each method and print the output to verify it is correct.
Agree with Jason. If you wanna test something, simply System.out.println() it. In your methods though, your return type is not a String but a void, so you could change that, and print it out on the main program run.
If not, just put the System.out.println() in your void methods. Shouldn't have much of a problem!
Implement a method
public void search (String searchString) { }
to iterate through the notes ArrayList until it
finds a note that contains the searchString.
It should then print either the item found or
the message "String not found".
So far, I have:
import java.util.ArrayList;
import java.util.Iterator;
/**
* A class to maintain an arbitrarily long list of notes.
* Notes are numbered for external reference by a human user.
* In this version, note numbers start at 0.
*
* #author David J. Barnes and Michael Kolling.
* #version 2008.03.30
*/
public class Notebook
{
// Storage for an arbitrary number of notes.
private ArrayList<String> notes;
/**
* Perform any initialization that is required for the
* notebook.
*/
public Notebook()
{
notes = new ArrayList<String>();
}
/**
* Store a new note into the notebook.
* #param note The note to be stored.
*/
public void storeNote(String note)
{
notes.add(note);
}
/**
* #return The number of notes currently in the notebook.
*/
public int numberOfNotes()
{
return notes.size();
}
/**
* Show a note.
* #param noteNumber The number of the note to be shown.
*/
public void showNote(int noteNumber)
{
if(noteNumber < 0) {
// This is not a valid note number, so do nothing.
System.out.println("invalid index given");
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number, so we can print it.
System.out.println(notes.get(noteNumber));
}
else {
System.out.println("there are fewer items in the notebook");
// This is not a valid note number, so do nothing.
}
}
public void removeNote(int noteNumber)
{
if(noteNumber < 0) {
// This is not a valid note number, so do nothing.
System.out.println("invalid index given");
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number.
notes.remove(noteNumber);
}
else {
System.out.println("there are fewer items in the notebook");
// This is not a valid note number, so do nothing.
}
}
/* Edit note.
* I tried to improve the formatting of the code below, but I'm completely
* unable to figure out how on earth anything of that should make sense
* and therefore the indentation is completely without any meaning.
*/
public void search (String searchString)
{
for each notes in ArrayList {
if notes = searchString;
System.out.println("String found"); + searchString
return end
}
if}
System.out.println("String not found");
}
}
But it is not working, and I am not able to work it out.
Several problems:
Your search method is actually outside the class.
The body of your search method makes no sense at all.
If you're counting on the monkeys writing Shakespeare, you'll be waiting a while.
To iterate over the array list, you can use a 'for-each' loop:
for (String note: notes) {
// Do something with note
}
This is very basic syntax. Have you seen it before? If not, you should start by reading a very basic tutorial to Java before attempting this homework.
Fundamentally you need to look at each item in your ArrayList and test to see if it matches the search condition. In Pseudocode
for each note in notes
{
if note equals searchString then
print "Found " + searchString
return
end if
}
print "not found"
Given that basic outline, want to take a second stab at coding it in Java?
Basically you want to loop over the elements, and for each one check whether it equals the element you are searching for. You can use a for loop or a foreach loop to do the actual iteration.
should you be checking if the whole note matches your searchstring, or if the note contains your searchstring?
i.e. given notes "foobar","baz","spam", should a search on "foo" return "foobar" or not match on anything?
so in pseudocode:
for each note in notes
{
if searchstring in note
{
print "Found :"+note
}
}
check this website http://pleac.sourceforge.net/pleac_java/arrays.html it may be useful
This example demonstrates using Scanner to read a file line by line (it does not perform a write operation) I don't know why I get an error when I try to compile. Could somebody explain the reason to me?. I'm using jcreatorLE and JDK 1.6 to run my program:
import java.io.*;
import java.util.Scanner;
public final class File_read {
public static void main(String... aArgs) throws FileNotFoundException {
ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
parser.processLineByLine();
log("Done.");
}
/**
* #param aFileName full name of an existing, readable file.
*/
public ReadWithScanner(String aFileName){
fFile = new File(aFileName);
}
/** Template method that calls {#link #processLine(String)}. */
public final void processLineByLine() throws FileNotFoundException {
Scanner scanner = new Scanner(fFile);
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
//ensure the underlying stream is always closed
scanner.close();
}
}
/**
* Overridable method for processing lines in different ways.
*
* <P>This simple default implementation expects simple name-value pairs, separated by an
* '=' sign. Examples of valid input :
* <tt>height = 167cm</tt>
* <tt>mass = 65kg</tt>
* <tt>disposition = "grumpy"</tt>
* <tt>this is the name = this is the value</tt>
*/
protected void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
//(no need for finally here, since String is source)
scanner.close();
}
// PRIVATE //
private final File fFile;
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
private String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
This is the result from running it:
--------------------Configuration: <Default>--------------------
C:\Users\administrador\Documents\File_read.java:15: invalid method declaration; return type required
public ReadWithScanner(String aFileName){
^
1 error
Process completed.
When you lifted that code from here :-), you renamed the class but not the constructor. Only constructors are allowed to not have return types.
I suggest you either rename the class back or rename the constructor.
I hope this isn't homework. As it stands, your educator would have an easy time proving plagiarism. You'll need to at least change the variable names as well as class names, you might want to also reformat it a bit including changing the order of methods in the class.
That's if it's homework. Which it's not, right? :-)
Your "ReadWithScanner" constructor needs to match the name of the class ("File_read")
public File_read(String aFileName){
fFile = new File(aFileName);
}
Your class is named File_read and your constructor is named ReadWithScanner. The warning is that your constructor needs to be named the same as the class.
The name of the class is File_read, so the constructor name should be File_read but you gave the name as ReadWithScanner that is why its complaining. Compiler thinking its a method name so expecting a return type.