Stuck On A Method/Class Reference Issue (JAVA Basic) - java

My aim was to create a little bit of code which allows my computer to randomly select how it refers to me. "Hello " + (randomly selected nickname) + ", how are you today?"
Pretty simple, right? Not to a noob like me!
Referenced Class
I gave it 4 choices of names, and it selects one at random and prints it out.
public class NameRef {
public static void main(String[] args){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("DJ");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Sir");
Random rand = new Random();
rand.nextInt(4);
System.out.println(nickNames.get(rand.nextInt(4)));
}
}
Main Class
I wanted this class to take the information from that secondary class' function and reference to it in my greeting.
public class CodeTesting extends NameRef {
public static void main(String[] args) {
System.out.println("Hello, " + /*The product from the NameRef*/ + " how are you?");
}
}
I don't know how I am supposed to reference that information? I've tried is a hundred ways!
I also tried to make a function in the secondary class that RETURNED a name string but then I wasn't able to reference that in my main class...
I am so confused. Any help as to where I'm going wrong would be great. Thanks.

Change main in NameRef to a function that returns String. So instead of System.out.println(nickNames.get(rand.nextInt(4)));, it should instead do return nickNames.get(rand.nextInt(4)). Then in CodeTesting class, call the function like this:
public class CodeTesting extends NameRef {
public static void main(String[] args) {
System.out.println("Hello, " + nameOfFunction() + " how are you?");
}
}
Where nameOfFunction is the name you call the function you created

public class NameRef {
public String getName(){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("DJ");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Sir");
Random rand = new Random();
rand.nextInt(4);
return nickNames.get(rand.nextInt(4));
}
}
public class CodeTesting extends NameRef {
public static void main(String[] args) {
NameRef nameRefObject = new NameRef();
System.out.println("Hello, " +nameRefObject.getName()+ " how are you?");
}
}

Related

Method and Variable Scope Issue in Java

I need help I cannot figure out how to fix the scope of my variables. I want this to be an example for my notes but have been on it for almost 2 hours.
public class methodPractice{
String streetName;
int streetNum;
public static void streetName()
{
String streetName = "Pope Ave.";
}
public static void streetNum()
{
int streetNum = 11825;
}
public static void main(String[] args)
{
streetName();
streetNum();
System.out.println("This is your home adress: " + streetNum +
streetName);
}
}
Thank you for your help.
You are shadowing the fields. Use this to make sure you get the fields, or a compile error.
public static void streetName()
{
this.streetName = "Pope Ave.";
}
public static void streetNum()
{
this.streetNum = 11825;
}
Here is your main method, with line numbers added:
1. public static void main(String[] args) {
2. streetName();
3. streetNum();
4. System.out.println("This is your home adress: " + streetNum + streetName);
5. }
A few points...
When line 2 runs, "streetName()" calls the static method below. The static keyword says you are free to call the method by itself – that is, you don't need an object; you don't need to call new methodPractice() first.
public static void streetName() {
String streetName = "Pope Ave.";
}
When line 3 runs, it's the same thing: "streetNum()" calls a different static method – again, totally fine to call this by itself.
public static void streetNum() {
int streetNum = 11825;
}
Line 4 is different, there are a few things going on. Your expectation is that "streetNum" finds the int that you declared on the class, but it doesn't work. Why? Because you defined that member with "int streetNum" – without "static". So what? Without being declared static, it means "streetNum" belongs to an object instance. What does that look like? Here's an example showing object creation, followed by setting the object member "streetNum" to 1.
methodPractice object = new methodPractice();
object.streetNum = 1;
You could work around this by declaring both of the non-static members to be static (static String streetName, and static int streetNum). Or you could leave them as is, and interact with them through an object instance (after doing new ..).

is there any way to copy often-used dynamic routines into a java method?

New to java, and I'm currently relying on lots of output messages to trace activity. I'd like a way to do this cleanly, to make 'semi-redundant' code as inconspicuous as possible.
Originally, I was doing this: (Note the System.out.println statements.)
package hamburger;
...
public class Hamburger extends Application {
...
public static void main(String args[]){
System.out.println("---> hamburger.Hamburger.main");
...
String [] drink = {"pepsi"};
NoCoke.onlypepsi(drink);
... ...
public class NoCoke
public static void main(String args[]){
System.out.println("---> hamburger.NoCoke.main");
...
static void justpepsi(String... commandIn){
System.out.println("---> hamburger.NoCoke.justpepsi");
...
try{ to get coke anyway...
Of course, when I moved things around or renamed stuff, all these literals had to be updated, so I started doing things dynamically using these three lines:
public class Hamburger
public static void main(String[] args) {
String nameClass = new Throwable().getStackTrace()[0].getClassName();
String nameMethod = new Throwable().getStackTrace()[0].getMethodName();
System.out.println("---> "+nameClass+"."+nameMethod);
public class NoCoke
public static void main(String args[]){
<AND HERE>
public static void justpepsi(String... commandIn){
<AND HERE>
It works fine:
---> hamburger.Hamburger.main
---> hamburger.NoCoke.main
---> hamburger.NoCoke.justpepsi
But I hate the way it looks, takes up space, etc.
Is there anything like a 'copy-book' in java? - a doc that contains executable code that can be dropped anywhere? Or is there a procedure to define the code as something like 'a String' that could be declared in the constructor, something like this:
StringThing nameMessageRoutine = new (whatever...) StringThing
"String nameClass = new Throwable()...<etc>...
System.out.println('---> '+nameClass+'.'+nameMethod);'"
...that I could just 'import' or 'refer to' like this:
public class Hamburger extends Application {
public static void main(String args[]){
import: nameMessageRoutine; //outside of the package member
public class NoCoke
public static void main(String args[]){
reference: nameMessageRoutine; //defined in the constructor
This method prints information about from where it was called:
static void printCurrent() {
final StackTraceElement ste = new Throwable().getStackTrace()[1];
String methodName = ste.getMethodName();
String className = ste.getClassName();
String lineNum = ""+ste.getLineNumber();
System.out.println(className + ", " + methodName + ", Line " + lineNum);
}
For example:
package randomTest;
public class MainClass {
public static void main(String[] args) {
printCurrent();
}
}
The output is
randomTest.MainClass, main, Line 131
EDIT:
I know this doesn't exactly answer the question, but it does accomplish the final goal of tracing code activity. To answer the question (as per the title), there is no way in pure Java to automatically insert routines into marked places.

Call data from a string array to another class

public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}

Instantiating and Updating Several Objects

Currently I am teaching myself Java but I came across a simple problem but have no one to ask from. From one of the exercises, I wrote a class and write a driver class that instantiates and updates several objects. I am confused by "instantiates and updates several objects." Here is what I mean: So here is my class:
public class PP43Car {
private String make = "";
private String model = "";
private int year;
public PP43Car(String ma, String m, int y)
{
make = ma;
model = m;
year = y;
}
public void setMake(String ma)
{
make = ma;
}
public String getMake()
{
return make;
}
public void setModel(String m)
{
model = m;
}
public String getModel()
{
return model;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public String toString()
{
String result = "Make of the vehicle: " + make +
" Model of the vehicle " + model +
" Year of the vehicle: " + year;
return result;
}
}
Which instantiates make, model and year. Then once I was writing the driver class, the way I began was:
import java.util.Scanner;
public class PP43CarTest {
public static void main(String[] args) {
PP43Car car1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the model of the vehicle:");
car1.getModel();
}
}
But this class produces error and here is where I am stuck. Do I keep on going with this or is this what is meant by "instantiating and updating several objects?"
import java.util.Scanner;
public class PP43CarTest {
static PP43Car car1;
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
car1 = new PP43Car("Millenia", "Mazda", 2011);
}
}
If the above code is correct, then can anyone show me how I can use the Scanner class to actually get the user input and update it that way because I would like to learn that as well?
Well, in your last fragment of code you are indeed instantiating an object, since you are doing:
car1 = new PP43Car("Millenia", "Mazda", 2011);
When you create a new object, you are creating a new instance of the class, so yes, you are instantiaing an object.
But you aren't updating it anywhere, because I think here updating means modifying the object, but you only create the object, not modify it...
Something like this would be an update:
car1.setYear(2013);
Since you are setting a different value for an attribute of the object, you are updating it...
EDIT: Try this code, it can't throw any exception, it's Java basics! I hope it clarifies your doubts...
public class PP43CarTest {
public static void main(String[] args) {
//Declaring objects
PP43Car car1;
PP43Car car2;
PP43Car car3;
//Instantiating objects
car1 = new PP43Car("Millenia", "Mazda", 2011);
car2 = new PP43Car("Aaaa", "Bbb", 2012);
car3 = new PP43Car("Ccc", "Ddd", 2012);
//Updating objects
car1.setMake("Xxx");
car1.setMake("Yyy");
car1.setYear(2013);
//Printing objects
System.out.println("CAR 1: " + car1.toString());
System.out.println("CAR 2: " + car2.toString());
System.out.println("CAR 3: " + car3.toString());
}
}

Simple ArrayList question

I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?
First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

Categories