Here is a program similar to the sinking battleship game from the book head first java. After compiling I am getting the error: "String cannot be converted to ArrayList Error" and ^ pointer point to the line I have two different files one with the main method and other a separate class. Whats wrong here.
Main method class
import java.util.Scanner;
public class SimpleDotComTestDrive{
public static void main(String[] args){
SimpleDotCom dot=new SimpleDotCom();
boolean repeat=false;
String[] locations={"2","3","4"};
dot.setLocationCells(locations); //^ where compiler points the error
Scanner input=new Scanner(System.in);
System.out.println("Lets Start");
while(repeat==false) {
System.out.println("Type your guess");
String userGuess=input.nextLine();
String result=dot.checkYourSelf(userGuess);
System.out.println(result);
if(result=="kill") {
repeat=true;
break;
}
}
} //close main
} //close test class
Separately saved class which is part of this program:
import java.util.ArrayList;
public class SimpleDotCom {
private ArrayList<String>locationCells;
public void setLocationCells(ArrayList<String> locs) {
locationCells=locs;
}
public String checkYourSelf(String userGuess) {
String result="miss";
int index = locationCells.indexOf(userGuess);
if(index>=0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result="kill";
}
else {
result="hit";
}
}
return result;
} //close check yourself method
} //close simple class
You are getting the error because setLocationCells() method accepts an ArrayList<String> and you are passing it a String Array by doing:
dot.setLocationCells(locations);
You should either replace your method to accept String[] instead of ArrayList<String> or change your code as follows:
dot.setLocationCells(new ArrayList<String>(Arrays.asList(locations));
You cannot have String[] locations={"2","3","4"}; and then parse it to the method setLocationCells(ArrayList<String> locs){ that requires the ArrayList.
So, there are more ways:
Convert the array to list with: new ArrayList<String>(Arrays.asList(locations);
Define the ArrayList instead:
ArrayList<String> list = new ArrayList<String>() {{
add("2");
add("3");
add("4");
}};
Change your method at all:
public void setLocationCells(String[] locs){
Collections.addAll(locationcells, locs);
}
Related
I was wondering how to reference an ArrayList a different method than it was declared in.
For example I am writing a program that allows me to create a playlist of songs, so in one method I have createAPlaylist and then another method I have shuffle().
In my playlist method I have created an ArrayList but I am having trouble using this arrayList in my shuffle method. There is some code below for context:
public static void createAPlaylist() {
try {
System.out.println("We have the following tracks:");
ArrayList<String> songs = new ArrayList<String>();
String firstSong = jukebox.allTracks.get(0).getTitle();
songs.add(firstSong);
for (int index = 0; index < count; index++) {
System.out.println(SPACES + (index + 1) + ". " + jukebox.allTracks.get(index).getTitle());
}
System.out.println("Select a track to add to the playlist: ");
int songNumber = input.nextInt();
String songSelected = songs.get(songNumber);
songs.add(songSelected);
input.nextLine();
} catch (Exception e) {
System.out.println("\nplease select a valid song number.");
}
}
This is what method parameters are for:
public static void createAPlaylist() {
ArrayList<String> songs = new ArrayList<>();
shuffle(songs);
}
public static void shuffle(ArrayList<String> songs) {
// Do stuff with your ArrayList here
}
You can the arraylist from the createAPlaylist method and pass that to shuffle method:
Like:
public static List<String> createAPlaylist() {
...
...
...
return songs;
}
/// and then in shuffle method receive that as parameter :
public static void shuffle(List<String> songs){
// access that songs list by
}
Or you could:
Instead of method variable declare that arraylist as class variable..
Like:
public class ClassName{
public static ArrayList<String> songs = new ArrayList<String>();
public static void createAPlaylist() {
...
...
...
// reset the songs.
songs = new ArrayList<String>();
...
}
/// and then in another method:
public static void suffle(){
// access that songs list by
List<String> createdSongs = ClassName.songs;
}
In Java, variables are only available within the context they are created - so if you create an ArrayList inside a method, you cannot access it outside of that method unless you store it in the method’s class, or you return the variable from the method it’s made it.
You can either declare the ArrayList outside of the method, as a class field, like so:
public class Foo {
private static ArrayList<String> arrayList = new ArrayList<String>();
public static void createAPlaylist() {
arrayList.add();
etc...
}
}
Or you could return the ArrayList from the method like so:
public class Foo {
public static void main(String[] args) {
ArrayList<String> arrayList = createAPlaylist();
}
public static ArrayList<String> createAPlaylist() {
ArrayList<String> songs = new ArrayList<String>();
// Your code here
// Note that you have to return the list from
// inside the catch block!
// I’d recommend creating the ‘songs’ ArrayList
// outside of the ‘try’ block, so that you can
// have a fallback if something fails in the ‘try’
return songs;
}
}
I don’t know if you intend to have this all static. I’d think it will work better as non static, but that’s a matter for another question, so I’ve left it as-is in the examples.
Sorry if this isn’t formatted perfectly - I’m on a mobile device and don’t have my IDE.
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.
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]);
}
}
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]
how do I get the read txt file into the main class?
//main class
public class mainClass {
public static void main(String[]args) {
load method = new load("Monster");
}
}
//scanner class
public class load {
public static void loader(String... aArgs) throws FileNotFoundException {
load parser = new load("resources/monsters/human/humanSerf.txt");
parser.processLineByLine();
log("Done.");
}
public load(String aFileName){
fFile = new File(aFileName);
}
public final void processLineByLine() throws FileNotFoundException {
//Note that FileReader is used, not File, since File is not Closeable
Scanner scanner = new Scanner(new FileReader(fFile));
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
scanner.close();
}
}
public 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("Stat is : " + quote(name.trim()) + ", and the value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
}
public final File fFile;
public static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
public String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
Which method do I call from the main class and what variables do I return from that method if I want the text from the file. If anyone has a website that can help me learn scanner(got this source code of the internet and only sort of understand it from JavaPractises and the sun tutorials) that would be great. thanks
First, you probably want to follow standard Java naming conventions - use public class MainClass instead of mainClass.
Second, for your methods, the public has a specific purpose. See here and here. You generally want to label methods as public only as necessary (in jargon, this is known as encapsulation).
For your question - in the Load class, you can append all the text from the file to a String, and add a public getter method in Load which will return that when called.
Add this at the start of Load:
public class Load {
private String fileText;
// ... rest of class
And add this getter method to the Load class. Yes, you could simply mark fileText as public, but that defeats the purpose of Object-Oriented Programming.
public getFileText(String aFileName){
return fileText;
}
Finally, use this new method for log. Note that there is no need to use Object.
private static void log(String line) {
System.out.println(line);
fileText += aObject;
}
You can now get the read file into the main class by calling method.getFileText()
Code was TL;DR
If you want to get all of the data from the load class's .txt file, then you need to write a method in load to get the lines. Something like this would work:
public String[] getFileAsArray() {
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(fFile);
while(in.hasNextLine())
lines.add(in.nextLine();
String[] retArr = new String[lines.size()];
return lines.toArray(retArr);
}