Now, I also just have a simple question on the client class below, an error I'm getting, how to fix that error, and properly print (this.toString())
import java.io.*;
import java.util.Scanner;
public class IndexClient
{
File file = new File("file.txt");
System.out.println(this.toString());
}
Basically, I am getting an error on the second to last line that says identifier expected right before the after the println and before the first parentheses. Why am I getting that error, how would I fix that error, and then how would I successfully print (this.toString())?
Update Number 1:
I am not sure that this is entirely necessary; however, if you need it, my toString() method is below:
public String toString()
{
String sb = "";
for (int d = 0; d < words.size(); d++)
{
sb += "The word: " + words.get(d) + System.lineSeparator();
}
return sb;
}
Update Number 2:
I really appreciate all the help and constructive criticism of the code that I can get. I hope I didn't turn this simple question into one too complex. Thank you very much :)
Update Number 3:
I am sorry for leaving so many notes. However, I was only just wondering if this is a common question that any of you guys see a lot because it seems like this comes up a lot in class, and the teacher assisstant can't answer the question. Thanks again :)
You can't use :
System.out.println(toString());
Out side a method, you can use it inside a method or you can create your main method :
public void myMethod(){
System.out.println(toString());
}
Or
public static void main(String args[]){
System.out.println(toString());
}
You cannot have code outside a method in a java class.
You must create an object of your class to access this.
A correct minimal implementation would look like that (taken from the Online Java IDE):
import java.lang.Math; // headers MUST be above the first class
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
OtherClass myObject = new OtherClass("Hello World!");
System.out.print(myObject);
}
}
// you can add other public classes to this editor in any order
public class OtherClass
{
private String message;
private boolean answer = false;
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?";
}
public String toString()
{
return message;
}
}
Related
I am attempting to write a program which asks users what their pet name is, species, finds out thirst level and gives a response accordingly.
I would appreciate if someone could help me with a problem im having, in each of the 2 methods askpetname and thirstlevel there are 2 strings i want accessible throughout the entire class without using global variables.
Can someone tell me what it is i am doing incorrectly or point me in the right direction.
Also, i understand that my excess use of methods for tedious tasks is bad practice but it helps with memorising syntax.
Thanks.
class dinoo
{
public static void main(String[] p)
{
explain();
output();
System.exit(0);
}
public static void explain()
{
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
public static String askpetname()
{
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
print("Awesome, cool dinosaur name, what species is " + petname+ " ?");
String petspecies = scanner.nextLine();
return petname, petspecies;
}
public static int thirstlevel()
{
Random ran = new Random();
int thirst = ran.nextInt(11);
int hunger = ran.nextInt(11);
return thirst,hunger;
}
public static String anger(int thirst, int hunger)
{
double angerscore = (thirst+hunger)/2;
String temper;
if(angerscore<=2)
{
temper = "Serene";
}
else if(3<=angerscore<=6)
{
temper= "Grouchy";
}
else if(6<angerscore)
{
temper = "DANGEROUS";
}
return temper;
}
public static String warning()
{
if (temper.equals("Serene"))
{
print("He's looking happy!");
}
else if(temper.equals("Grouchy"))
{
print("Ahhh hes a bit "+temper+", you better start feeding him before he gets mad!");
}
else if(temper.equals("DANGEROUS"))
{
print("GET OUT OF THERE, HES " + temper+"!!!. He will have to be put down for everyones safety.");
}
}
public static void output()
{
print(askpetname() + "'s, thirst level is "+thirstlevel()+"/10");
return;
}
public static String print(String message)
{
System.out.println(message);
return message;
}
}
That code won't compile since you can't have:
return string1, string2;
or
else if(3<=angerscore<=6)
Instead of trying to return multiple Strings, your best bet is to create a class, say called Pet, one that holds String fields for the pet's name, a Species field for its species, as well as any other fields for hunger, thirst ... that would best encapsulate all the data that makes up one logical "pet" as well as a methods such as getAnger() that returns a value for anger depending on the Pet's state. Then you can create and return a viable Pet object from your creational method.
Also, your code has lots of compilation errors, suggesting that you could improve the way that you create your code. Never try to add new code to "bad" code, to code that won't compile. If possible, use an IDE such as NetBeans, Eclipse, or IntelliJ to help you create your programs. The IDE's will flag you if any of your code contains compilation errors, and then the key is: don't add new code until you've first fixed the existing compilation error. If you can't use an IDE, then you must compile early and often, and do the same thing -- fix all errors before adding new.
First, I would recommend shooting through a tutorial first before attempting this, do all the hello worlds covering scope, objects, arrays and functions. Get familiar with Object Oriented Style, although thats not even procedural programming ... nothing returns 2 objects ... always 1 (it could be an array containing many objects, but an array is a single object)
Moving on,although this is terrible coding practice, but its ok for a beginner,since your functions are all static, create a private static variable inside each function and create getter functions
//convert
String petname = scanner.nextLine();
// To this
private static String petname = scanner.nextLine();
// Then add this below it
public static String getPetName()
{
return petname;
}
and same for every piece of data you need.
Now remove the return statement from all of your functions and declare return type as void
Then call all functions from Main,
askpetname();
thirstlevel();
then print final output (after you have called the functions) as such
System.out.println("Petname: " + getPetname + " ThirstLevel: " + getThirstLevel() + " HungerLevel: " + getHungerLevel);
So I had to write a code that takes a word and reverse it I got it to work but for my homework I had to make it into two classes a tester class and a main class how do I do that?
public static void main(String args[])
{
String original = "";
String reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
{
reverse = reverse + original.charAt(i);
}
System.out.println("Reverse of entered string is: "+reverse);
}
You create two classes. You can even put a main method in both of them.
public class Homework {
public static void main(String[] args) {
// Code here to prompt user for string and to print reversed string
}
static String reverse(String input) {
// Code here to do the actual reverse logic, returning reversed string
}
}
public class HomeworkTest {
public static void main(String[] args) {
test("Hello", "olleH");
test("This is a test", "tset a si sihT");
}
private static void test(String input, String expected) {
String rev = Homework.reverse(input);
System.out.println(input + ": " + rev);
if (! expected.equals(rev))
System.out.println(" ** NOT AS EXPECTED: " + expected);
}
}
You can now run the Homework for manual testing, or the HomeworkTest class for automatic testing.
You could get the original String in the Main-class and hand it to the second class to execute the for-loop. The second class then returns the reversed String so that the Main-Class can print it out.
The second class could contain a static method which reverses the String (executes the for-loop) or you can create an object of the second class and and this Object the original String to reverse.
There are several ways to do this. Most trivially, you could make a static function in a Test class, like so:
class Test
{
public static void runTest(String args[])
{
//same as your above program
}
}
But that is probably not what your teacher wants. Instead, you could make a Test class that reverses a set of strings.
class Test
{
public static void runTests()
{
//iterate through a list of hard-coded strings to test
}
}
You would then make a separate function in a Reverser class and the Test.runTests() function would test the Reverser class.
However, there are standardized ways of doing this. One common way is called JUnit. If you are using Eclipse, try this page for instructions.
The simplest way is to
Divide your code into a function public String reverse(String input)
Create new Tester class
Add test method in tester class public void test()
Prepare assertions to test your function assert reverse("ola").equals("alo") : "First assertion failed"
In main function run new Tester().test();
To make assertions working you have to run jvm with -ea option
I have the following code:
import java.util.*;
public class Room {
ArrayList<Bed> beds = new ArrayList<Bed>();
private int BedNumber;
public void createBed(boolean isDouble) {
beds.add(new Bed(isDouble));
BedNumber++;
}
public int howManyBeds() {
return BedNumber;
}
public static void main(String[] args) {
Room p = new Room();
p.createBed(true);
p.createBed(false);
Bed test = p.beds.get(0);
System.out.println(test);
}
}
public class Bed {
private boolean isDouble;
public Bed(boolean isDouble) {
this.isDouble = isDouble;
}
public String bedSize() {
if (isDouble) {
return "Double Bed";
} else {
return "Single Bed";
}
}
}
When I compile it, Eclipse informs me that there are errors present in the code and asks me if I wish to proceed. When I do, I end up with a totally unexpected output - Bed#14ae5a5
I'm so confused as to what might be causing this. I imagine it's something stupidly simple but I'm just not seeing it.
Can anyone see what I'm missing?
UPDATE ----
Found the error which I've corrected below. I was printing the object reference instead of calling a method...
This is now printing the correct result, however, Eclipse is still informing me that something is wrong at compilation.
Is my code badly written? Can anyone determine why Eclipse isn't happy?
Your compilation errors are due to your attempt to declare two public classes in one Java file.
As for the output, you are attempting to print the Bed object--which results in Object.toString() being printed.
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So, it prints the name of the class, "Bed," with an # sign followed by the hex value of its hash, 14ae5a5.
The println method of System.out actually calls the toString method of the parameter, in this case, a bed. However, toString is not present in your Bed class! So what did it do? It calls the toString method of Object, which returns Bed#XXXX where XXXX is the memory location of your bed.
To solve this, just add a toString method to your class. Remember to add #Override to overwrite the toString method of Object
#Override
public String toString () {
//return a string representation here
}
In Java, where should I aim (I enjoy figuring it out myself) to get, with sample data:
I am Sam I am a
the output:
I am Sam I am - letter to remove a
I m Sm I m
Basically, it is to "Remove all instances of the specified removal letter from the original sentence"
As this is for a class, I am limited with what I can do. For this assignment I am stuck with the given classes/constructors and am not allowed to make any more unless it is noted, which in my case, is to create another constructor class; Anyway, that has been the real challenge as it is hard to get help (No matter how many times I've googled!) with it being so specific and I new to the language.
Here is what I was given:
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private char lookFor;
public LetterRemover()
{
//call set
}
//add in second constructor
public void setRemover(String s, char rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
This is what I've done so far:
import java.util.Scanner;
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
//add in second constructor
public void setRemover(String s, String rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I tried changing the char to a string for the "lookfor" to use the replace all method which seemed after a lot of research and the best way to get the letters out.
Is there any noticeable mistakes and where should I look to fix them? I do not really want the right code, or for anyone to "do" the work for me. I really want to try and figure it out. But I need a little help in pointing in the right direction to get my desired output :)
Let me know if there is any other details or whatnot, this is also , this is also my first time using the site. There were many similar questions to this, but as I really am a beginner I struggled to understand people's explanations
--Edit--
Moving to my runner class, this is what I wrote, trying to get for the desired output. I am not really sure how to deal with output as I really have just started learning to write them myself.
I keep getting a void error though:
import static java.lang.System.*;
public class LetterRemoverRunner
{
public static void main( String args[] )
{
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
}
}
Try the below code and confirm this is what your requirement is.
LetterRemoverRunner.java
public class LetterRemoverRunner {
public static void main(String args[])
{
LetterRemover test = new LetterRemover ();
test.setRemover("I really want dumplings","l");
System.out.println(test.toString());
System.out.println("Removed :"+test.removeLetters());
}
}
LetterRemover.java
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
public void setRemover(String s, String rem)
{
this.sentence = s;
this.lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I'm pleased you suggested you don't want the answer - much better way to learn!
I'm not sure you've understood constructors yet. You're line:
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
Is going to give you a null pointer error because it's calling setRemover on test before test has been constructed. You should be constructing the object with its sentence and lookFor values before calling setRemover.
Here are some things you might want to look at:
The String.indexOf method will look for a certain character or string and tell you where to find it (or if it isn't in the string at all).
The String.substring method allows you to take part of a string using string positions
You can build a new string by concatenating substrings together
Using a while loop you can continue using indexOf until the target cannot be found.
As you've pointed out, you can also use one of the replace methods to replace the target with "".
Doing a java assignment in CSE 205 at ASU, and I'm having a hard time understanding parsing. I've looked through our online textbook, and parsing rarely comes up and it's never given a full explanation. I've looked through the java api documentation a few times and I never understand what it's saying, so I hope someone isn't too frustrated as to explain how to do it.
The class is:
BankParser
The BankParser class is a utility class that will be used to create bank objects from a string. The BankParser class cannot be instantiated. It has the following method:
public static Bank bankParser(String lineToParse)
The bankParser method's argument will be a string in the following format:
bankName/bankID/city,state
A real example of this string would be:
Bank Arizona/10001/Phoenix,AZ
The bankParser method will parse this string, pull out the information, create a new bank object, set the attributes of the object, and return it.
So far this is my setup:
public class BankParser {
public static Bank bankParser(String lineToParse) {
}
}
Also, in my Bank class I have this toString method:
public String toString() {
String printInfo = ("\nBank name:\t" + bankName + "\nBank ID:\t" + bankID + "\nBank address:\t" + bankAddress + "\n");
return printInfo;
It gives me 2 markers in eclipse: that this overrides java.lang.Object.toString, and that the return type is missing. What does this all mean?? The return type is String, I don't see what the problem is with that, but the override I'm clueless
EDIT; This is what I've come up with for bankParser
public static Bank bankParser(String lineToParse) {
String[] returnValue = lineToParse.split("/");
Bank temp = new Bank();
temp.setbankName(returnValue[0]);
temp.setbankID(returnValue[1]);
temp.setbankAddress = (returnValue[2]); //this one won't work, see below
return temp;
}
}
And THESE are the methods in Bank and Address that apply to bankParser
public void setBankName(String bank1) {
bankName = bank1;
}
public void setBankID(String bankID1) {
bankID = bankID1;
}
public void setBankAddress(String city, String state) {
bankAddress.setCity(city);
bankAddress.setState(state);
}
In Address.java:
public void setCity(String city1) {
city = city1;
}
public void setState(String state1) {
state = state1;
}
I would use library like Apache Common CSV for reading and writing.
Reader in = new StringReader("bankName/bankID/city,state");
Iterable<CSVRecord> parser = CSVFormat.newBuilder()
.withDelimiter('/')
.parse(in);
for (CSVRecord csvRecord : parse) {
...
}
Your bankParser method is empty. It needs to return a Bank object, and Java will complain until you do this. You could always have it return null for now til, make it at least a compilable stub you figure this out:
public static Bank bankParser(String lineToParse) {
Bank returnValue = null;
// TODO: create a Bank object, assign to returnValue
return returnValue;
}
As for your override bit, are you getting an error message? Or a warning? The code you've posted seems kosher, so it should compile. Please show the actual full message.
As for your actual parsing, I'd use String#split("/") to split the lineToParse into an array of tokens and then work with each token, create arguments for a Bank constructor call and create a Bank object.
i.e., code to show the concept:
String text = "Bank Arizona/10001/Phoenix,AZ";
String[] tokens = text.split("/");
System.out.println(java.util.Arrays.toString(tokens));