[英]I am not getting any output with this java code. When I run the code without calling methods, that is all the code is in the main method, it works
'This declares matrixA, randomNumber, and size' '这声明了 matrixA、randomNumber 和 size'
static int size;
static int matrixA [][] = new int [size][size];
static Random randomNumber = new Random();
'This method asks the user to enter an int. '此方法要求用户输入一个 int。 The input is used to set the size of an array'
输入用于设置数组的大小'
static void setSize() {
Scanner input = new Scanner(System.in);
System.out.println("Enter size");
size = input.nextInt();
}
'This method fills the array with random numbers and prints the array. '这个方法用随机数填充数组并打印数组。 This is producing no output.'
这没有产生任何输出。
static void fillMatrixA() {
for (int i = 0; i < matrixA.length; i++) {
System.out.println();
for (int j = 0; j < matrixA[i].length; j++) {
matrixA[i][j] = randomNumber.nextInt(10);
System.out.println(matrixA[i][j]);
}
}
}
'When I call this method in the main method there is no output. '当我在 main 方法中调用此方法时,没有输出。 The program has only one class.
该计划只有一堂课。 What could the problem be?'
可能是什么问题?
When things seem screwy, (a) check your assumptions, (b) engage a debugger .当事情看起来很奇怪时,(a)检查你的假设,(b)使用调试器。
Your assumption that matrixA
has a length greater than zero is incorrect.您认为
matrixA
的长度大于零的假设是不正确的。 A debugger would show the length to be zero.调试器会显示长度为零。
When you initialize a static
variable within the declaration statement, that code executes when the class is loaded.在声明语句中初始化
static
变量时,该代码会在加载类时执行。 So new int [size] [size]
executed very early, before your other code.所以
new int [size] [size]
在你的其他代码之前很早就执行了。 When that line executed, it used the current value of size
, which was zero.当该行执行时,它使用
size
的当前值,该值为零。 Why zero?为什么是零? Because that is the default value assigned to a primitive
int
.因为这是分配给原始
int
的默认值。
Later, in your setSize
method, you change the value of size
from zero to the value input by the user.稍后,在您的
setSize
方法中,您将size
的值从零更改为用户输入的值。 But that has no effect on your two-dimensional array.但这对您的二维数组没有影响。 That array was initialized to a length of zero long before the
setSize
method executed.在执行
setSize
方法之前,该数组的长度已初始化为零。
See your code run live at Ideone.com .查看您的代码在 Ideone.com 上实时运行。 You can fork that code, and play with it.
您可以分叉该代码并使用它。
The problem you experienced is one reason why I like to do all my initializing within a constructor.您遇到的问题是我喜欢在构造函数中进行所有初始化的原因之一。 I rarely use initialization with declaration syntax.
我很少使用带有声明语法的初始化。 But other reasonable programmers may differ on this point.
但其他理性的程序员可能在这一点上有所不同。
By the way, your code has much room for improvement.顺便说一句,您的代码还有很大的改进空间。
First and foremost, you are likely overusing static
.首先,您可能过度使用
static
。 Anything marked static
is not object-oriented.任何标记为
static
的东西都不是面向对象的。 If you are writing much non-object-oriented code in Java, you are missing out on much of the value of Java.如果您在 Java 中编写大量非面向对象的代码,那么您将错过 Java 的大部分价值。 As a beginning student of Java, you should generally avoid using
static
in general.作为 Java 的初学者,您通常应该避免使用
static
。 Even in real work, use static
as a last-resort generally.即使在实际工作中,通常也使用
static
作为最后的手段。
Another tip:另一个提示:
Scanner
when done using them.Scanner
。 Use try-with-resources syntax to do so more easily and briefly.static
factory method rather than a public
constructor.static
工厂方法而不是public
构造函数。 Taking that all into account, write a class to represent our problem domain , the business matter of managing a matrix whose height and width are of equal dimensions.考虑到所有这些,编写一个类来表示我们的问题域,即管理高度和宽度相等的矩阵的业务问题。
package work.basil.example.squarematrix;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class SquareMatrix
{
private int matrix[][];
private SquareMatrix ( final int size )
{
// … Add code here validate passed argument.
this.matrix = new int[ size ][ size ];
this.randomize();
}
public static SquareMatrix ofSize ( final int size )
{
return new SquareMatrix( size );
}
public void randomize ( )
{
for ( int[] row : matrix )
{
for ( int columnIndex = 0 ; columnIndex < row.length ; columnIndex++ )
{
row[ columnIndex ] = ThreadLocalRandom.current().nextInt( 0 , 10 ); // ( inclusive , exclusive )
}
}
}
public int[][] toArray ( )
{
// Code taken from: https://stackoverflow.com/a/53397359/642706
int[][] copy = Arrays.stream( this.matrix ).map( int[] :: clone ).toArray( int[][] :: new );
return copy;
}
public CharSequence report ( )
{
StringBuilder sb = new StringBuilder();
for ( int[] row : this.matrix )
{
sb.append( Arrays.toString( row ) );
sb.append( "\n" ); // Using Unix convention of LINE FEED as a delimiter. https://www.fileformat.info/info/unicode/char/000a/index.htm
}
return sb ;
}
}
Notice how this class has a specific purpose: manage the content of our matrix.注意这个类有一个特定的目的:管理我们矩阵的内容。 It is not responsible for interacting with a user.
它不负责与用户交互。 It is not responsible for running our larger app.
它不负责运行我们更大的应用程序。
Also notice how the two-dimensional array is contained, and marked private
.还要注意二维数组是如何被包含和标记的
private
。 This is known as encapsulation in OOP.这在 OOP 中称为封装。 By encapsulating, we are free to internally use a two-dimensional array today, while leaving the door open to using some other data structure tomorrow.
通过封装,我们今天可以在内部自由使用二维数组,同时为明天使用其他数据结构敞开大门。 Other code calling upon our
SquareMatrix
class does not know or care anything about its internals.调用我们
SquareMatrix
类的其他代码不知道也不关心它的内部结构。
And notice how the toArray
method makes a copy of our internally-managed two-dimensional array.注意
toArray
方法是如何复制我们内部管理的二维数组的。 We do not want to provide direct access to our internal array, for a couple reasons.出于几个原因,我们不想提供对内部数组的直接访问。 One reason is that direct access would break the encapsulation discussed above.
一个原因是直接访问会破坏上面讨论的封装。 Another reason is that we cannot trust the calling programmer;
另一个原因是我们不能信任调用程序员。 he/she may alter the content.
他/她可以更改内容。
Next we create an "app" class, to provide a user-experience for accessing the bounty that is our square matrix.接下来我们创建一个“app”类,为访问我们的方阵提供一种用户体验。
package work.basil.example.squarematrix;
import java.util.Scanner;
public class SquareMatrixApp
{
public static void main ( String[] args )
{
SquareMatrixApp app = new SquareMatrixApp();
int size = app.askUserForSize();
SquareMatrix squareMatrix = SquareMatrix.ofSize( size );
CharSequence report = squareMatrix.report();
System.out.println( "report = \n" + report );
int[][] array = squareMatrix.toArray();
System.out.println( "array.length: " + array.length );
}
private int askUserForSize ( )
{
try (
Scanner scanner = new Scanner( System.in ) ;
)
{
System.out.println( "Enter size: " );
int size = scanner.nextInt();
// … Add code here to validate inputs. For example, no negative numbers allowed.
return size;
}
}
}
Notice here how the code for interacting with the user to gather input is segregated to its own method.注意这里与用户交互以收集输入的代码是如何被隔离到它自己的方法中的。 That user-interface code does not know about, nor does it care about, matrices.
该用户界面代码不知道也不关心矩阵。
When run.跑的时候。
Enter size:
3
report =
[9, 3, 7]
[0, 7, 2]
[0, 7, 7]
array.length: 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.