2016-04-22 16 views
0

ユーザーが同じ座標を2回入力したかどうかを確認するコードを書くのに手伝ってもらえますか?ユーザーが座標を繰り返し入力するのを確認するMATLAB

コードの一部:

rc = input('Enter your next move [row space column]: '); 
       row = rc(1); %users coordinates 
       col = rc(2); 
          if row<0 || col<0 
          disp('Please enter positive coordinates'); 
          rc = input('Enter your next move [row space column]: '); 
          row = rc(1); 
          col = rc(2); 
          end 
          if row>size || col>size 
          disp('Please enter cordinates with in the game board'); 
          rc = input('Enter your next move [row space column]: '); 
          row = rc(1); 
          col = rc(2); 
          end 

私が出回っ正と値の大きすぎるためにチェックしましたが、今私は、ユーザーが同じ二度座標入力しないことを確認するチェックしたい、と彼らの場合エラーメッセージを表示します。 ありがとうございました ありがとう

+0

を、私は強く 'while'ループと' if'文を交換示唆そうしないと、エンドユーザーに許可している:あなたはそれをすぐにテストできるように

次のコードは、完全な実施例でありますあなたのプログラムをクラッシュさせる。プログラムを中断するための['error'](http://mathworks.com/help/matlab/ref/error.html?requestedDomain=www.mathworks.com)メッセージを表示しますか、またはユーザーに' 'input '](http://mathworks.com/help/matlab/ref/input.html)のようにしていますか?彼らは異なったものです。 – codeaviator

+0

私は、ユーザーが繰り返し座標を入力した後に再度ユーザー入力を要求したいと思います。 whileループでは、私はそうするでしょう:行<0 || col <0のように? – katDouglas

+0

正確に。ユーザーが '行||を繰り返す場合、ユーザー入力を要求しますか? col'または 'row && col'?ちなみに、あなたは '=='演算子に精通していますか? – codeaviator

答えて

0

ユーザーが同じ座標を2回入力しないようにするには、有効な座標のすべてのペアを配列に格納して、次回ユーザーが新しい座標ペアを入力すると、すでに存在するかどうかを確認できます。

row座標の場合はrowvcol座標の場合はcolvの2つの配列を作成しました。

その後、私は==relational operatorと組み合わせlogical operatorsany&を使用して、以下のwhile条件を実装:

% Check that the point is not repeated. 
while any((rowv == row) & (colv == col)) 

だから、限り、ユーザーは、彼/彼女がするまで再度お試しすることが求められます繰り返しcoorinatesに入ると有効なペアが入力されます。

% Game board size. 
size = 4; 

% Ask for number of points. 
n = input('Number of points: '); 

% Preallocate arrays with -1. 
rowv = -ones(1,n); 
colv = -ones(1,n); 

% Iterate as many times as points. 
for p = 1:n 
    % Ask for point coordinates. 
    rc = input('Enter your next move [row space column]: '); 
    row = rc(1); 
    col = rc(2); 

    % Check that coordinates are positive. 
    while row<0 || col<0 
     disp('Please enter positive coordinates'); 
     rc = input('Enter your next move [row space column]: '); 
     row = rc(1); 
     col = rc(2); 
    end 

    % Check that coordinates are within the game board. 
    while row>size || col>size 
     disp('Please enter cordinates within the game board'); 
     rc = input('Enter your next move [row space column]: '); 
     row = rc(1); 
     col = rc(2); 
    end 

    % Check that the point is not repeated. 
    while any((rowv == row) & (colv == col)) 
     disp('Coordinates already exist. Please enter a new pair of cordinates'); 
     rc = input('Enter your next move [row space column]: '); 
     row = rc(1); 
     col = rc(2); 
    end 

    % The point is valid. 
    % Store coordinates in arrays. 
    rowv(p) = rc(1); 
    colv(p) = rc(2); 
end 
関連する問題