My code is like this:
public class Test() {
String [] ArrayA = new String [5]
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0])
}
}
I've tried various methods (No pun intended) but none worked. Thanks for any help I can get!
public class Test {
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
public Test(){ // Your Constructor
method1(arrayA[0]); // Calling the Method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, you can just call new Test();
OR if you want the method to be called from your main class by creating an instance of Test you may write:
public class Test {
public Test(){ // Your Constructor
// method1(arrayA[0]); // Calling the Method // Commenting the method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, create an instance of test in your main class.
Test test = new Test();
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
test.method1(arrayA[0]); // Calling the method
And call your method.
EDIT:
Tip: There's a coding standard that says never start your method and variable in uppercase.
Also, declaring classes doesn't need ().
If we're talking about passing arrays around, why not be neat about it and use the varargs :) You can pass in a single String, multiple String's, or a String[].
// All 3 of the following work!
method1("myText");
method1("myText","more of my text?", "keep going!");
method1(ArrayA);
public void method1(String... myArray){
System.out.println("The first element is " + myArray[0]);
System.out.printl("The entire list of arguments is");
for (String s: myArray){
System.out.println(s);
}
}
try this
private void Test(){
String[] arrayTest = new String[4];
ArrayA(arrayTest[0]);
}
private void ArrayA(String a){
//do whatever with array here
}
Try this Snippet :-
public class Test {
void somemethod()
{
String [] ArrayA = new String [5] ;
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1 (String[] A) {
System.out.println("Here's where I need ArrayA[0]"+A[0]);
}
public static void main(String[] args) {
new Test().somemethod();
}
}
The Class name should never had Test()
I am not sure what you are trying to do. If it is java code(which it seems like) then it is syntactically wrong if you are not using anonymous classes.
If this is a constructor call then the code below:
public class Test1() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0]);
}
}
should be written as this:
public class Test{
public Test() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1(String[] ArrayA){
System.out.println("Here's where I need " + ArrayA[0]);
}
}
Related
How can I pass string variable or String object from one class to another?
I've 2 days on this problem.
One class get data from keyboard and second one should print it in console.
Take some help from the below code:-
public class ReadFrom {
private String stringToShow; // String in this class, which other class will read
public void setStringToShow(String stringToShow) {
this.stringToShow = stringToShow;
}
public String getStringToShow() {
return this.stringToShow;
}
}
class ReadIn {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // for taking Keyboard input
ReadFrom rf = new ReadFrom();
rf.setStringToShow(sc.nextLine()); // Setting in ReadFrom string
System.out.println(rf.getStringToShow()); // Reading in this class
}
}
There are two ways:
create an instance of your printer class and evoke the method on the printer object:
public class MyPrinter
{
public void printString( String string )
{
System.out.println( string );
}
}
in your main:
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
or 2. you create a static method in your printer class and evoke it in your main:
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
in your main:
MyPrinter.printStringWithStaticMethod( input );
Write a method inside your second class with System.out.println(parameter);
Make the method static and then invoke this in first method like
ClassName.methodName(parameter)
Inside class that accepts Scanner input
variableName ClassName = new Classname();
variablename.methodToPrintString(string);
A textbook can always help in this situation.
I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.
Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}
While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.
This example:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
Will work, however, it would be better if it was more like this...
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}
You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.
public class SomeClass {
NumberList numberlist; // Definition
....
Then in your create() function just say:
numberlist= new NumberList(length, offset); // Initialization
Declare numberList outside your methods like this:
NumberList numberList;
Then inside create() use this to initialise it:
numberList = new NumberList(length, offset);
This means you can access it from any methods in this class.
I'm completely new to Java and I'm trying to set up a test for it. But how do I call a method from the test class?
Right now I'm trying with a public method, and making a new instance of the class Hangman, but the call to the method doesn't work.
Hangman.java:
public class Hangman extends Applet implements ActionListener{
public String[] getWordArray(){
/* Enter the wordslist, separated by a | here: */
String str = "computer|"
+ "radio|"
+ "calculator|"
+ "teacher|"
+ "bureau|"
+ "police|"
+ "geometry|"
+ "president";
String[] temp;
/* delimiter */
String delimiter = "\\|";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
return temp;
}
}
HangmanTest.java:
public class HangmanTest {
Hangman hangman = new Hangman();
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void testGetWordArray() {
int expected = 8;
int actual = hangman.getWordArray().length();
Assert.assertEquals(expected, actual);
}
}
You have a syntax error. It is int actual = hangman.getWordArray().length;, not int actual = hangman.getWordArray().length();. The length of array is an attribute, not a method. All other datastructures (like ArrayList) have a method for this.
From reading tutorials and practicing Java, I have come across a problem. I have created a String ArrayList, added string to it. However I want one method which allows me to add more string to this arrayList and another method which allows me to display this arrayList. below is my attempt to solve this problem. My code only prints an empty Array List
class apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static void addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
}
static ArrayList GetArrayList() {
ArrayList<String> destinationArray = new ArrayList<String>();
return destinationArray;
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Didn't you forget adding addString() to getArrayList()?
Your variable destinationArray is declared in a method, it meens that it only exists inside this method outside addString() the object does not exist anymore and you can't access it in other methods. To do it you have to declare it as a class variable like that :
class apples{
ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args)
When your program is executed, in fact it executes the main method, as a result if you want to execute your method addString() you will have to call it in the main function. It will look like that :
public static void main(String[] args)
{
this.addString();
this.viewArrayList(); //prints a empty arraylist
}
Create a Object of a ArrayList and pass reference to different methods. Example create a ArrayList Object in main class and pass it to addString & display method.
public static void main(String[] args){
List<String> destinationArray = new ArrayList<String>();
viewArrayList(destinationArray);
displayArrayList(destinationArray);//prints a empty arraylist
}
public static void addString(List destinationArray ){
destinationArray.add("example1");
destinationArray.add("example2");
}
...
I would do something like this:
class apples
{
private ArrayList<String> array = new ArrayList<String>();
public void addString(String addString)
{
this.array.add(addString);
}
public ArrayList<String> GetArrayList()
{
return array;
}
}
One problem is that you use a different array list for each method. Every time you use the keyword new you are creating a new (and empty) list.
At the top of your class create the ArrayList once...
private ArrayList<String> myList = new ArrayList<String>();
then refer to myList in all your other methods without assigning it a new value.
public ArrayList<String> getArrayList() {
return myList;
}
public void addSomeStrings() {
myList.add("Some String");
myList.add("Some Other String");
}
and don't be afraid to walk through a Java tutorial. This is a fundamental concept and you may get pretty frustrated if you don't shore up your foundation.
Compile and run following program.
import java.util.ArrayList;
class Apples {
static ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args) {
System.out.print("First time");
viewArrayList();
addString("Example1");
addString("Example2");
addString("Example3");
System.out.print("Second time");
viewArrayList();
addString("Example4");
addString("Example5");
System.out.print("Third time");
viewArrayList();
}
public static void addString(String example) {
destinationArray.add(example);
}
static ArrayList getArrayList() {
return destinationArray;
}
public static void viewArrayList() {
System.out.println(getArrayList());
}
}
The scope of the array object is the problem here. You are adding string to 1 array and trying to print another array. Remove the static block and the array declaration in addString(). Declare the array next to the class definition like this,
class apples {
ArrayList destinationArray = new ArrayList();
.. ....
It should work.
Code:
public class Apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static ArrayList<String> addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
return destinationArray;
}
public static ArrayList<String> GetArrayList() {
return addString();
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Output:
[example1, example2]
What's the issue here?
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
UserInput input = new UserInput();
input.name();
}
This complains:
<identifier> expected
input.name();
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
input.name() needs to be inside a function; classes contain declarations, not random code.
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
I saw this error with code that WAS in a method; However, it was in a try-with-resources block.
The following code is illegal:
try (testResource r = getTestResource();
System.out.println("Hello!");
resource2 = getResource2(r)) { ...
The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about "try-with-resources" here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html