我正在研究一个用arraylist创建难题的类,我在FillWords方法方面遇到问题, 这是一种要求用户输入单词以填充2D ArrayList的益智游戏的方法。当我运行代码时,当我只有一个输入下一行时,此方法会给我输入双输入下一行吗?
[![Image1]] [1] [1]:https://i.stack.imgur.com/jpoZ9.png
import java.util.*;
public class simplePuzzle
{
static Scanner input = new Scanner(System.in);
static Random rd = new Random();
public static void main(String[] args)
{
char[][] words;
int size;
displayPurpose();
size = getSize();
words = new char[size][size];
fillWords(words,size);
//displayWords(words,size);
}//of main
/**
* This method displays the main purpose of this program
*/
private static void displayPurpose()
{
System.out.println("----------------------------------------------------------------------------------");
System.out.println(" This program creates a simple word puzzle ");
System.out.println("----------------------------------------------------------------------------------");
}//of displayPurpose
/**
* This method asks the user for a size input
* @param size the size of the puzzle
*/
private static int getSize()
{
//asks the user for the size of the puzzle and checks if the input is between 5 and 10, stores the var in an int dataType and returns it to size
int size;
System.out.print("What is the size of the puzzle you would like to create (>=5 and <= 10): ");
size = input.nextInt();
if (size >= 5 && size <= 10 )
{
return size;
}
else
{
System.out.println("******Invalid size, MUST be ()>= 5 and <= 10)****** ");
System.out.print("What is the size of the puzzle you would like to create (>=5 and <= 10): ");
size = input.nextInt();
return size;
}
}//getSize
/**
* This method asks the user for puzzle words and stores them in the 2d array list
*/
private static void fillWords(char[][] words, int size)
{
// Asks the user for puzzle words, word cannot exteed the size of the puzzle and the letter of the word starts at random number on the puzzle grid.
String puzzleWord;
int wordLength;
int wordStart;
System.out.printf("%nEnter %d words, each word should be no more than %d characters long", size, size );
System.out.println("");
for(int i= 0; i < size; i++)
{
do{
System.out.println("Please enter a word:" );
puzzleWord = input.nextLine();
if (puzzleWord.length() > size){
System.out.printf("Word cannot fit in the puzzle. It MUST be <= %d characters in length", size);
}
}while(puzzleWord.length() > size);
for(int k= 0; k < puzzleWord.length(); k++){
wordLength = puzzleWord.length();
wordStart = size - wordLength ;
int v = rd.nextInt(wordStart) + 0;
//------------------------MAX----MIN
words[i][k]= puzzleWord.charAt(v);
}
}
}//fillWords
}//end
答案 0 :(得分:1)
我认为您在使用扫描仪时遇到问题,请添加
input.nextLine();
读取大小时在行之后。看起来应该像这样:
int option = input.nextInt();
input.nextLine();