Does anyone know how to call a variable into another method? Doing an assignment for school and really struggling. (Variable that I want to call is arrayOfEarth by the way.)
public static void readDataArray(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("sample.xyz")));
int rows = 2500000;
int columns = 3;
double[][] arrayOfEarth = new double[rows][columns];
while (input.hasNextLine()) {
for (int a = 0; a < arrayOfEarth.length; a++) {
String[] line = input.nextLine().trim().split("/t ");
for (int b = 0; b < line.length; b++) {
arrayOfEarth[a][b] = Double.parseDouble(line[b]);
}
}
}
System.out.println(Arrays.deepToString(arrayOfEarth));
}
public static List<Double> CoordinatesAbove(double altitude) {
List<Double> CoordinatesAbove = new ArrayList<>();
for (int c = 0; c < arrayOfEarth.length; c++) {
CoordinatesAbove.add(arrayOfEarth[c][2]);
}
CoordinatesAbove.removeIf(d -> d < altitude);
return CoordinatesAbove;
}
Just move it to the class level and make it static (otherwise the static method can't use it)
private static double[][] arrayOfEarth;
public static void readDataArray(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("sample.xyz")));
int rows = 2500000;
int columns = 3;
arrayOfEarth = new double[rows][columns];
while (input.hasNextLine()) {
for (int a = 0; a < arrayOfEarth.length; a++) {
String[] line = input.nextLine().trim().split("/t ");
for (int b = 0; b < line.length; b++) {
arrayOfEarth[a][b] = Double.parseDouble(line[b]);
}
}
}
System.out.println(Arrays.deepToString(arrayOfEarth));
}
public static List<Double> CoordinatesAbove(double altitude) {
List<Double> CoordinatesAbove = new ArrayList<>();
for (int c = 0; c < arrayOfEarth.length; c++) {
CoordinatesAbove.add(arrayOfEarth[c][2]);
}
CoordinatesAbove.removeIf(d -> d < altitude);
return CoordinatesAbove;
}
Make your readDataArray method return the value to the caller, and have whoever is calling the CoordinatesAbove method pass the value to it.
To return the value and to accept it as a parameter:
public static double[][] readDataArray(String filename) throws FileNotFoundException {
...
System.out.println(Arrays.deepToString(arrayOfEarth));
return arrayOfEarth;
}
public static List<Double> CoordinatesAbove(double altitude, double[][] arrayOfEarth) {
...
}
To capture the return value of readDataArray and to pass it to CoordinatesAbove:
double[][] arrayOfEarth = readDataArray(...)
List<Double> list = CoordinatesAbove(altitude, arrayOfEarth);
It is arguably better to make the flow of information explicit like this, than hiding the flow by writing the results to a common global variable in one method and reading the variable in the other.
Related
I want to pass the result of this method.
static public int[][] scanCube(Cube c){
int counter0 = 0;
Scanner in = new Scanner(System.in);
counter0 = 0;
while(counter0 < 4){
cube[BOTTOM][counter0] = Integer.parseInt(in.nextLine());
counter0++;
}
return cube;
}
To this constructor so that I can call the method above in main.
private Cube(int [][] Scancube){
cube = new int[Scancube.length][];
for(int i = 0; i < Scancube.length; i++){
cube[i] = Arrays.copyOf(Scancube[i], Scancube[i].length);
}
}
So I can use this in main like this.
public static void main(String[] args) {
Cube c = new Cube();
Cube.scanCube(c);
System.out.println(c);
Cube.solve(c);
}
int[][] value= Cube.scanCube(c);
System.out.println(value);
Cube.solve(value);
Try like this, as you need to store the value first in the variable of the type you are using then you can pass the variable as a input for your next method.
So I have been creating a Word-Puzzle which I recently got stuck on a index out of bounds problem. This has been resolved however the program is not doing what I would like it to do. The Idea i that the test class will print 3 words in an array e.g. [FEN, GNU, NOB] (and yes they are apparently real english words). Then check to see if the first letter of each word combined is a word and so forth e.g. FGN if so add it to the next ArrayList else start again. Ideal output would be [FEN, GNU, NOB] [FGN, ENO, NUB] for example. However the current output is [FEN, GNU, NOB] [SOY, SOY, SOY] or [FEN, GNU, NOB] [].
The Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Test 1: size 3");
int size = 3;
Puzzle.WordPuzzleGenerator.generatePuzzle(size);
}
}
WordGenerator:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
break;
}
puzzleListX.add(randomXWord);
if (puzzleListX.size() == size){
finished = false;
}
}
}
System.out.print(puzzleListY);
System.out.print(puzzleListX);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
}
I think you are confusing yourself with that finished variable. Replace the while condition with puzzleListX.size() != size and your code should work.
I want to create a game and I need to read file from the notepad
when I use my loadfile.java alone, it work very well. Then, I would like to copy my data into datafile.java as it will be easier for me to do the fighting scene. However, I can't copy the array in my loadfile.java to the datafile.java and I don't understand why.
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
public class loadfile
{
static String filename = "Save.txt";
static int size = 4;
static int s;
static int[] number;
static String[] line;
private static void load() throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (reader.readLine()!= null)
{
size++;
}
size -= 4;
reader.close();
line = new String[size];
number = new int[size];
BufferedReader reader2 = new BufferedReader(new FileReader(filename));
for (int i = 0; i < size; i++)
{
line[i] = reader2.readLine();
}
reader2.close();
for (int i = 4; i < size; i++)
{
number[i] = Integer.parseInt(line[i]);
}
}
public static String[] getData()
{
return line;
}
public static int[] getNumber()
{
s = size - 4;
int[] num = new int[s];
for (int i = 0; i < s; i++)
{
num[i] = number[i+4];
}
return num;
}
public static int getDataSize()
{
return size;
}
public static int getNumberSize()
{
return size - 4;
}
This is my loadfile.java
I use the file with 4 names and 9 * n int in the notepad as I want to check whether I have the character first before I read the file. However, before I can handle this problem, I got another problem that I can't copy the array into my datafile.java
The datafile.java is separate with two constructor. One is for Starting the game and one is for loading the data. The constructor with the (int num) is the problem I have. First, I would like to show the java first:
import java.util.Arrays;
import java.io.*;
public class datafile
{
private static String[] data;
private static int[] number;
private static String[] name;
private static int[] a, d, s;
private static int[] hp, maxhp;
private static int[] mp, maxmp;
private static int[] lv, exp;
public datafile()
{
initialization();
name[0] = "Pet";
a[0] = 100;
d[0] = 100;
s[0] = 100;
hp[0] = 500;
mp[0] = 500;
maxhp[0] = 500;
maxmp[0] = 500;
exp[0] = 100;
lv[0] = 1;
}
public datafile(int num) throws IOException
{
initialization();
loadfile l = new loadfile();
for (int i = 0; i < l.getNumberSize(); i++)
{
number[i] = l.getNumber()[i];
}
for (int i = 0; i < l.getDataSize(); i++)
{
data[i] = l.getData()[i];
}
for(int i = 0; i < 4; i++)
{
name[i] = data[i];
}
for(int i = 0; i < 4; i++)
{
a[i] = number[1+(i*9)];
d[i] = number[2+(i*9)];
s[i] = number[3+(i*9)];
hp[i] = number[4+(i*9)];
mp[i] = number[5+(i*9)];
maxhp[i] = number[6+(i*9)];
maxmp[i] = number[7+(i*9)];
lv[i] = number[8+(i*9)];
exp[i] = number[9+(i*9)];
}
}
public static String getName(int n)
{
return name[n];
}
public static int getAttack(int n)
{
return a[n];
}
public static int getDefense(int n)
{
return d[n];
}
public void initialization()
{
name = new String[3];
a = new int[3];
d = new int[3];
s = new int[3];
hp = new int[3];
mp = new int[3];
maxhp = new int[3];
maxmp = new int[3];
lv = new int[3];
exp = new int[3];
}
public static void main (String[] args) throws IOException
{
new datafile(1);
}
}
When I run the program, the debugging state this line
data[i] = l.getData()[i];
as an error
I don't know what wrong with this line and I tried so many different ways to change the way the copy the method. However, it didn't work
The error says this:
Exception in thread "main" java.lang.NullPointerException
at datafile.<init>(datafile.java:38)
at datafile.main(datafile.java:92)
I hope you guys can help me with this problem because I don't want to fail with my first work
in your datafile(int num)
you call
loadfile l = new loadfile();
but you never call the load() method on you loadfile
l.load();
Edit: my bad, I didn't see your initialization method, but regardless, I'm going to stick with my recommendation that you radically change your program design. Your code consists of a kludge -- you've got many strangely named static array variables as some kind of data repository, and this suggests that injecting a little object-oriented design could go a long way towards creating classes that are much easier to debug, maintain and enhance:
First I recommend that you get rid of all of the parallel arrays and instead create a class, or likely classes, to hold the fields that need to be bound together and create an ArrayList of items of this class.
For example
public class Creature {
private String name;
private int attack;
private int defense;
// constructors here
// getters and setters...
}
And elsewhere:
private List<Creature> creatureList = new ArrayList<>();
Note that the Creature class, the repository for some of your data, should not be calling or even have knowledge of the code that loads the data, but rather it should be the other way around. The class that loads data should create MyData objects that can then be placed within the myDataList ArrayList via its add(...) method.
As a side recommendation, to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.
My apologize, I have a class on my Project, called test01.java. And i used the library from Tadaki Graphlib contained many class. On of them is Graph.java.
Test01.java:
public class test01 extends Graph{
public test01(String name, int n) {
super(name);
public test01(String name, int n) {
super(name);
graphLib.Vertex vList[] = new graphLib.Vertex[n];
for (int i = 0; i < n; i++) {
vList[i] = new graphLib.Vertex(String.valueOf(i));
addVertex(vList[i]);
}
int deg = 0;
System.out.println("<---------- Random val ---------->");
addArc(vList[0], vList[1], String.valueOf(0)); deg++;
addArc(vList[1], vList[0], String.valueOf(1)); deg++;
System.out.println("Vertex-0 with Vertex-1");
System.out.println("Vertex-1 with Vertex-0");
int k = 2;
int l;
int m=0;
Random randomval = new Random();
int isAvailInt [] = new int[n];
while (k<n) {
for(l=0;l<k;l++){
isAvailInt [l]= Integer.parseInt(vList[l].toString());
m=isAvailInt[l];
}
int chosen = randomval.nextInt(m);
addArc(vList[k], vList[chosen], String.valueOf(k));
System.out.println("Vertex-"+k+" with Vertex-"+chosen+
" exp = " + String.valueOf(k));
k++;
}
}public static void main(String args[]) {
int n;
String num = JOptionPane.showInputDialog("Masukkan nilai jumlah iterasi = ");
String degnum = null;
n = Integer.parseInt(num);
int deg []= new int [n];
test01 t = new test01("test",n);
System.out.println("<---------- Vertex-i = Degree-i ------------>");
graphLib.Graph g= new Graph("test");
int [][]adj = g.getAdjacent();
System.out.println(adj[0][0]);
for (int i=0; i<t.getSize();i++){
for (int j=0; j<t.getSize();j++){
}
}}
and one other class called Graph.java
public class Graph extends GraphBase { int adjacent[][] = null;
public Graph(String name) {
this.name = name;
vertexes = Utils.createVertexList();
arcs = Utils.createArcList();
a2vHead = new HashMap<>();
a2vTail = new HashMap<>();
v2a = new HashMap<>();
}
public int[][] getAdjacent() {
int n = vertexes.size();
adjacent = new int[n][];
for (int i = 0; i < n; i++) {
adjacent[i] = new int[n];
for (int j = 0; j < n; j++) {
adjacent[i][j] = 0;
}
}
if (directed) {
for (int i = 0; i < n; i++) {
Vertex v = vertexes.get(i);
for (Arc a : v2a.get(v)) {
Vertex t = a2vTail.get(a);
int l = vertexes.indexOf(t);
adjacent[l][i]++;
}
}
} else {
for (int i = 0; i < n; i++) {
Vertex v = vertexes.get(i);
for (Arc a : v2a.get(v)) {
Vertex t = a2vTail.get(a);
if (!t.equals(v)) {
int l = vertexes.indexOf(t);
adjacent[i][l]++;
adjacent[l][i]++;
}
}
}
}
checkConnectedness();
return adjacent;
}}
From above, method - int [][] Adjacent() - has an array return value:
return adjacent;
Then I want to received it with array variable declared:
int [][]adj = g.getAdjacent();
But when I run the program, the code :
System.out.println(adj[0][0]);
Has appeared error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
I've declare the variable vertexes in Graph.java that extended from other class, GraphBase.java:
vertexes = Utils.createVertexList();
How do I obtain an array value form a variable adjacent in Graph.java to test01.java and how do I display it with System.out.println() ?
Well you haven't shown where vertexes is initialized (or even declared) in Graph. I suspect it's empty, so when you execute this code:
public int[][] getAdjacent() {
int n = vertexes.size();
adjacent = new int[n][];
...
return adjacent;
}
... you'll end up with an empty array. That would cause the problem you've seen. You can easily check the size in your main method:
System.out.println(adj.length);
I suspect you'll find it's 0. Either that, or adj[0].length is 0.
It's not clear how you expect the Graph to find any vertexes - you don't supply it with any, or even the value of n. You just call the constructor with a string:
graphLib.Graph g= new Graph("test");
Unless that's meant to be the name of a file which is loaded in the constructor, there's nowhere for it to get data from. You need to take a step back and think about where you expect the data to come from, then make sure that it can actually flow through your program. The problem isn't getting the array reference back to main - the problem is that the array is empty.
I doubted about this line returning 0.
int n = vertexes.size();
You can reproduce this issue by running below code
int adjacent[][] = new int[0][];
System.out.println(adjacent[0][0]);
You will get the same exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
To solve this issue
Make sure before proceeding vertexes have expected values.
This is my program that makes some calculations to a numbers into the array named "initialMarks". However I would like to fill the initialMarks array from another class using scanner.Could you help me to figure it out how to do that? Is it possible to outprint the result array "result" in a third class?
public class testingN
{
public static void main(String[] args)
{
int [] initialMarks = new int [4];
int [] result = new int [6];
result[0] = computedMarks(initialMarks[0], initialMarks[1])[0];
result[1] = computedMarks(initialMarks[2], initialMarks[3])[1];
for(int i=0; i< result.length; i++)
System.out.println(result[i]);
}
public static int [] computedMarks(int mark1, int mark2)
{
int [] i= new int [6];
for (int j = 0; j < i.length; j++)
{
if ((mark1 < 35 && mark2 > 35) || (mark1 > 35 && mark2 < 35))
{
i[j] = 35;
}
else
{
i[j] = (mark1 * mark2);
}
}
return i;
}
}
Your other class can have a method that returns a stream, and you can feed that into your Scanner's constructor.
In your other class's String getInitialMarks() method:
// Generate a string with all the "marks" as "stringWithMarks", separated by "\n" characters
InputStream is = new ByteArrayInputStream( stringWithMarks.getBytes( "UTF-8" ) );
return is;
Then in your first class, otherClass:
Scanner scanner = new Scanner(otherClass.getInitialMarks());
And proceed to read in the marks as if it were user input.
public class testingN
{
static int [] result = new int [6];
static int [] initialMarks = new int [4];
public static void main(String[] args)
{
Declaring result as class member (global variable) and being static should help your cause
Example: using from another class
public class AnotherClass {
public static void main(String[] args) {
// example
testingN.result[0] = 4;
System.out.println(testingN.result[0]);
}
}
Edit: Run the code below Here. You'll see it works just fine.
class testingN
{
static int [] result = new int [6];
static int [] initialMarks = new int [4];
}
public class AnotherClass {
public static void main(String[] args) {
// example
testingN.result[0] = 4;
System.out.println(testingN.result[0]);
}
}