简体   繁体   English

这个java代码我没有得到任何输出。 当我在不调用方法的情况下运行代码时,即所有代码都在 main 方法中,它可以工作

[英]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:另一个提示:

  • Separate user-interface code from business logic code.将用户界面代码与业务逻辑代码分开。
  • Use local state generally.一般使用本地状态。 Avoid global variables.避免全局变量。 Pass needed info as arguments.将所需信息作为参数传递。
  • Close your resources such as Scanner when done using them.完成使用后关闭您的资源,例如Scanner Use try-with-resources syntax to do so more easily and briefly.使用 try-with-resources 语法可以更轻松、更简洁地执行此操作。
  • Consider using a 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.

相关问题 运行以下Java代码时出现此错误 - I am getting this error when I run the below java code 我收到看似简单的 Java 代码的奇怪错误。 我在这里做错了什么? - I'm getting weird errors for seemingly simple Java code. What am I doing wrong here? 我的代码收到 ArrayIndexOutOfBoundsException 异常。 这个设置正确吗? - I am getting an ArrayIndexOutOfBoundsException with my code. Is this setup correctly? 为什么我在 java 代码中遇到无法访问的语句错误。 需要帮助来解决这个错误 - why am I getting unreachable statement error in java code. need help to solve this error 我从comboBox调用的方法将不会运行所有代码,而只会运行其中的一部分 - the method I am calling from the comboBox will not run all the code, it only runs part of it 我不确定为什么代码不会对 output 进行任何声明。 当我在我的 IDE 中运行它时,没有任何输出 - I am not sure why the code will not output any statements. When I run it in my IDE nothing is outputted 我想使用Java代码为多个浏览器运行TestNG套件。 有什么办法吗? - I want to run my TestNG suite for multiple browsers using Java code. Is there any way for the same? 我执行以下代码时,发生“ main”线程中的“ java.util.NoSuchElementException”异常。 - “ Exception in thread ”main“ java.util.NoSuchElementException ” error is occured when i execute the following code. 为什么我在Java代码中得到此输出? - Why I am getting this output in my Java code? 运行此代码时无输出 - No output when I run this code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM