初学者:如何返回用户输入?

时间:2017-04-02 13:43:50

标签: java class variables input types

我是Java的新手,我在使用这段代码时遇到了麻烦:

import java.util.Scanner;

public class BattleshipLogic {

    private final int rows;
    private final int cols;

    private final boolean[][] hits;
    private final boolean[][] ships;

    public BattleshipLogic(int numRows, int numCols) {
        this.rows = numRows;
        this.cols = numCols;

        this.hits = new boolean[rows][cols];
        this.ships = new boolean[rows][cols];
    }

    public void startGame() {
        placeShips();
        boolean gameOver = false;
        // draw field for the first time
        drawUI();

        while (!gameOver) {
            Target target = askForTarget();
            processTarget(target);
            drawUI();
        }
    }

    private Target askForTarget() {
        Target t = new Target();
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter your target:");
        t = input.nextInt();
        return t;
    }

    /*
     * This is just an example. You have to draw the ships by yourself.
     * If you don't like the way the UI is drawn, make your own stuff!
     */
    private void drawUI() {
        // draw the ui, see blatt01/oberfläche.txt for an example
        System.out.println("Schiffeversenken");
        System.out.println("================");
        System.out.println();

        // columns
        System.out.print("    ");
        for (int col = 0; col < this.cols; col++) {
            System.out.print(col + " ");
        }
        System.out.println();
        System.out.print("   _");
        for (int col = 0; col < this.cols; col++) {
            System.out.print("__");
        }
        System.out.println();
        for (int row = 0; row < this.rows; row++) {
            System.out.print(Character.toChars(3 + row));
            System.out.print(" |");

            System.out.println();
        }
    }

    private void placeShips() {
        // do useful stuff to place the ships here
        // see Blatt01 for rules
    }

    private void processTarget(Target target) {

    }

    /**
     * This class only holds the position
     * of a target.
     */
    private class Target {

        public int row;
        public int col;
    }
}

我每次尝试编译时都会出现此错误:

错误:不兼容的类型:int无法转换为BattleshipLogic.Target

我知道类型不同,但Target是什么类型的? 如何将用户输入分配给t?

提前非常感谢!

2 个答案:

答案 0 :(得分:0)

将int值赋给

  

类型的目标

你需要一个

  

getter和setter方法

在你的

e.g。

public class Target
{
  private int myValue;
  public void setMyValue(int myValue)
  {
     this.myValue=myValue;
  }
  public int getMyValue()
 {
      return myValue;
 }
}

然后在你的askForTarget()方法

t.setMyValue(input.nextInt());
return t;

如果你想在其他调用方法中使用int in t,你可以使用t方法

t.getMyValue();

答案 1 :(得分:0)

我想你想这样做。

Image