I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
This is my main method -
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = methods.createBoard();
userInput = methods.input();
}
}
And this is my methods class -
import java.util.Scanner;
public class methods {
//Create board method
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
//Take a guess method
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes and methods therefore I create lots of them.
You'll have to create a new instance of Main and methods first or alternatively declare the createBoard() and input() methods static.
Here is the code snippet:
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.run();
}
private void run() {
methods me = new methods();
int[] playBoard = me.createBoard();
int userInput = me.input();
}
}
Also, as per the naming convention rules for the class name it should be Methods instead of methods.
You haven't declared the variable playBoard being used inside Main. Did you intend to use board2 instead. I guess you want something like below:
board2 = new methods().createBoard();
userInput = new methods().input();
You need to create an object of class methods, in order to access instance methods.
Related
I'm trying to declare a 2D array of integers, set its size in the constructor, and change the array's values in a method. When I compile this , I get "Cannot store to int array because "this.a" is null". I'm not sure what I'm doing wrong.
public class arrays {
int[][] a;
public arrays(){
int[][] a = new int[10][10];
}
public void m(){
a[0][0] = 1;
System.out.println(a[0][0]);
}
public static void main(String[] args){
arrays Ar = new arrays();
Ar.m();
}
}
int[][] a = new int[10][10];
This is a combination of int[][] a; and a = new int[10][10]; - int[][] a; declares a new variable. It has the same name as your field, and thus now two different things, both named a, are in 'scope'; the local variable 'wins' - a = new int[10][10]; creates a new array and then assigns a reference to it to your local variable named a, not to the field named a. The constructor then ends, and all local variables are tossed away, because that's what always happens to local variables once a method/constructor exits: They disappear. In other words, you've created a new array but nothing is referring to; your field named a is not pointing at it because you didn't change that.
Just a = new int[10][10]; will get the job done, as now there is no local variable also named a and thus a now refers to the field you have.
Or, even simpler, get rid of your constructor entirely, and initialize your array as you declare it:
public class Arrays {
int[][] a = new int[10][10];
public void m() {
a[0][0] = 1;
System.out.println(a[0][0]);
}
public static void main(String[] args) {
Arrays ar = new Arrays();
ar.m();
}
}
It is all about scoping.
1- You have a property called int[][] a in your class.
2- You have another int[][] a, which is a local variable in your constructor because you defined another int[][].
So, as #Turing85 said,just remove int[][] type definition inside your constructor and that line should be a = new int[10][10];
Additional information:
When you define another int[][] a in your constructor, there is more than one a. While assigning new int[10][10] to a, the closest one in terms of scope(which is inside the constructor) is used. It may be useful for you to exercise scoping.
You have to declare the size before you are initializing the array
public class CustomArrays {
int[][] a = new int[10][10];
public void m(){
a[0][0] = 1;
System.out.println(a[0][0]);
}
public static void main(String[] args){
CustomArrays Ar = new CustomArrays();
Ar.m();
}
}
or this
public class CustomArrays {
int[][] a = new int[10][10];
CustomArrays() {
a[0][0]=1;
}
public void m(){
System.out.println(a[0][0]);
}
public static void main(String[] args){
CustomArrays Ar = new CustomArrays();
Ar.m();
}
}
and
public class CustomArrays {
int[][] a;
public CustomArrays() {
a = new int[10][10];
a[0][0] = 1;
}
public void m() {
System.out.println(this.a[0][0]);
}
public static void main(String[] args) {
CustomArrays Ar = new CustomArrays();
Ar.m();
}
}
all work.
First of all I am new to JAVA, so I still dont understand everything and how it works. But I was working on something and was wondering if it could be done like this.
import java.util.Scanner;
public class Main {
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
int Result = y + z;
sc.close();
return Result;
}
public static void printText(){
System.out.println(Result);
}
public static void main(String args[]) {
calc();
printText();
}
}
In the first method I was calculating the "Result" and in the second I just wanted it to make it so that it takes the "Result" and prints it.. but How I understand is that what happens in a method stays in the method. But I was wondering if it is possible to let method "printText" access the int from "calc".
I know I could place the code into the main and print it from there, but still it buggs me if it could be done like that :)
You can't access a local variable from a different method, no. (Once the method has completed, the local variable doesn't exist any more.) However, you can use the return value from your calc method, and pass that to the printText method:
public static void printText(int result) {
System.out.println(result);
}
public static void main(String args[]) {
int result = calc();
printText(result);
}
In order to do something like that1, you would need to give Result visibility. Since your methods are static it would also need to be static. Also, don't call close on a Scanner wrapping System.in (that's a global, and you can't re-open it). Something like,
private static int Result;
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
Result = y + z;
return Result;
}
1As opposed to using the returned value, or passing it into your second method.
I'm working on a Guessing Game that will uses arrays to store both the names of all the players and their guesses. I'm fairly new to arrays, so my plan to get user input into the array was to get them to enter the amount of people playing, set that up as a variable and then use a loop to keep asking for names until I reached the necessary amount of names for the stated number of players. However, I am running into what probably is a very simple problem with the loop. Here's a small bit of my code thus far:
public class GuessGame {
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
The problem is, I'm getting an error regarding the variables in my loop, w and j. The error statement says something to the effect of it cannot find the symbols for class w or class j. I don't intend for them to be classes, and I've run similar code in other projects without a hitch, so I really don't know what's going wrong here. I'm sure it's something stupidly simple, but *'ve been stuck at this wall for some time now and can't really progress until I get this sorted. This is part of a project with three separate classes. The class posted here, a Player class, and a Tester class, which is my main method. I had the whole thing working in a more simplified form earlier, but now I need to adjust it for actual player input and the arrays. Regardless, the tester class is supposed to be my main class. I am using Netbeans if it matters. Thank you. Here are the other two classes for reference:
package GuessGame;
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
and
package GuessGame;
import java.util.Random;
public class Player {
int number = 0; //where guess goes
String name;
public void guess() {
Random r = new Random();
number = 1 + r.nextInt(21);
System.out.println("I'm guessing " + number);
}
}
All your code needs to be in a method. You cannot have anything except variable declarations at the class level. Move all this into a method, for example public static void main(String[] args) main method.
public class GuessGame {
public static void main (String[] args)
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
public class GuessGame {
public void getPlayerName()
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
public static void main (String[] args)
{
GuessGame gg = new GuessGame();
g.getPlayerName();
}}
You can put in the methos as well and execute in the main method. But, if you declaring any variable inside the method (local variable), the variable must be initialised. Refer here for more details.
public class GuessGame
{
static int w = 0;
int[] Players = new int[100];
static String[] PlayerNames = new String[100];
public static void main(String[] args) {
// TODO Auto-generated method stub
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
Everything should be in a method except variables.Class is template for variables and methods !!
I need to access an array that is in a different class without using a getter. I have a scanner passed to a method which creates the array then calls a method to recursively fill the array with the data from a file. I then need to access the toString method and use the array from that class (Student[] list).
Public class Test
{
public static void main(String[] args) throws IOException
{
int actual = 0;
File input = new File("input.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
Scanner scan = new Scanner(input);
C155.createList(scan);
actual = C155.getSize();
// writer.write(C155.toString(C155.list, ??????));
writer.close();
}
}
public class C155 {
public static final int MAXSIZE = 22;
private static int size = 0;
public static Student[] createList(Scanner scan)
{
Student[] list = new Student[MAXSIZE];
return populateList(list, scan);
}
private static Student[] populateList( Student[] list, Scanner scan )
{
Student s;
if ( size < MAXSIZE && scan.hasNext() )
{
s = new Student(scan.next(), scan.next(),scan.next(),
scan.nextDouble(), scan.nextInt());
list[size] = s;
size++;
System.out.println(s);
return populateList(list, scan);
}
else
return list;
}
public static String toString(Student[] list, int n)
{
String all= "All Students \n";
for (int x = 0; x <= n; x++)
{
all += list[x].toString() + "\n";
}
return all;
}
I need to call the toString method (which requires the Student[] list)from the Test class but do not really know the best way to besides creating a get method.
As a note, all the methods in class C155 are static, which is probably not the best approach.
To answer your question though, your method createList(Scanner scan) has a return type of Student[]. That's where you would obtain a reference to that array in your main method.
Scanner scan = new Scanner(input);
Student[] studentArray = C155.createList(scan); <------
actual = C155.getSize();
writer.write(C155.toString(studentArray, studentArray.length())); <------
writer.close();
Why do you need to access the list if you return it by method? Just do this:
Student[] list = C155.createList(scan);
writer.write(C155.toString(list, list.length()));
I am trying to make a program to count words of a string.
The following is my code, and the errors coming in my code and I am unable to correct them:
import java.util.*;
class string1 {
public static int wordcount() {
String str;
Scanner s1= new Scanner(System.in);
System.out.println("Enter String:");
str=s1.nextLine();
int count=WCount(str);
System.out.println("Count="+count);
}
public static int WCount(String str) {
int l=str.length();
int count=0;
for(int i=0;i<l;i++) {
if(str.charAt(i)==' ')
count++ ;
}
if(count>0)
count++ ;
return(count);
}
}
public static void main (String s[]) {
string1 ss=new string1();
ss.wordcount();
}
Error :
java:25: class, interface, or enum expected
public static void main(String s[]) {
^
C:\Users\coocl\Desktop\java\string1.java:27: class, interface, or enum expected
ss.wordcount();
^
C:\Users\coocl\Desktop\java\string1.java:28: class, interface, or enum expected}3 errors
Process completed.
You main is out of the class. Declare it inside the class.
The main method belongs inside your class. When you run java to execute your compiled code, it will try to run the main method that belongs to the class that you specify. More generally, methods can't be declared outside classes in java: all methods must belong to a class.
Note that since your methods wordcount and WCount are both static, you don't need to create a string1 instance to use them, you can just call them on the class in main :
string1.wordcount();
Finally, in java, it is conventional to begin class names with uppercase, e.g. String1, see these Naming Conventions.
You have an extra } after WCount.
The main method must be inside a class, not outside. You have two ways:
Move it inside your string1 class.
Move it inside a class in the same *.java file
public class Main {
public static void main (String s[]) {
string1 ss=new string1();
ss.wordcount();
}
}
Bad practice:
string1 ss=new string1();
ss.wordcount();
First char in Java class name must be UPPER and
First char in Java method and fields name must be LOWER case;
All chars in JAVA constants (static final) name must be UPPER case;
wordCount() = static method and create object (string1 ss=new string1()) is not true.
Static fields and methods need call from class name (not instance class).
ClassName.(method/field)
Must be String1.wordCount()
Your code have multiple problem (in "{}", "return" in wordcount())
See code:
public class Test {
public static int wordcount() {
String str;
Scanner s1 = new Scanner(System.in);
System.out.println("Enter String:");
str = s1.nextLine();
int count = WCount(str);
System.out.println("Count=" + count);
return count;
}
public static int WCount(String str) {
int l = str.length();
int count = 0;
for (int i = 0; i < l; i++) {
if (str.charAt(i) == ' ')
count++;
}
if (count > 0)
count++;
return (count);
}
public static void main(String s[]) {
Test.wordcount();
}
}