- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
首先,我不确定我是否在这个问题的标题中表达了正确的问题,如果是这样,我深表歉意。
我的问题是 - 我正在使用列表 ADT 来模拟选择游戏。这个想法是一群 child 围成一圈坐着唱一首儿歌。每个 child 说一个押韵的单词,直到完成押韵。最后一个说韵的人出局了。然后从下一个 child 开始押韵。最后剩下的 child 是赢家。
应用程序将从键盘读取游戏中的玩家数量和韵律。将创建两个列表,一个用于玩家,一个用于押韵。 arraylists 使用方法的接口(interface)。
我正在编写代码以循环遍历两个列表,至少一次(我认为),以便沿着韵律遍历玩家,找出谁将被淘汰。一旦那个人被淘汰,玩家列表将缩减一位(押韵列表保持不变),并重新开始循环。
这是 doRhyme() 方法。
到目前为止,我的问题是当我运行我在代码中的内容时,我的返回是这样的:
Please enter the number of players
(It should be an integer value greater than or equal to 2):5
The players list is: 1 2 3 4 5
Please enter a rhyme:
One Two Three Four Five
Player 1: One
Player 2: Two
Player 5: Three
Player null: Four
Player null: Five
Rhyme performance error!
The players list is: 5
The winner is: 5
我用一二三四五作为押韵只是为了测试代码。我希望这不会让任何人感到困惑。
输出代码应该如下所示:
Please enter the number of players
(It should be an integer value greater than or equal to 2):5
The players list is: 1 2 3 4 5
Please enter a rhyme: One Two Three Four Five
Player 1: One
Player 2: Two
Player 3: Three
Player 4: Four
Player 5: Five
Removing player 5
The players list is: 1 2 3 4
Player 1: One
Player 2: Two
Player 3: Three
Player 4: Four
Player 1: Five
Removing player 1
The players list is: 2 3 4
and so on until only one player is left....
这里包括的是到目前为止的代码。任何帮助将不胜感激。与此同时,我将继续找出正确的代码。
public class RhymeGame
{
public static void main(String args[])
{
ListInterface<Integer> players = null;
ListInterface<String> rhyme = null;
int max;
int position = 1;
max = getInt();
players = new AList<Integer>();
for(int i = 1; i <= max; i++)
{
players.add(i);
}
System.out.println("The players list is: " + players);
rhyme = getRhyme();
while(players.getLength() > 1)
{
position = doRhyme(players, rhyme, position);
System.out.println("The players list is: " + players);
System.out.println();
}
System.out.println("The winner is: " + players.getEntry(1));
}//end of main
//Requires user to input the number of players.
private static int getInt()
{
Scanner input;
int result = 10; //default value is 10
try
{
System.out.print("Please enter the number of players\n(It should be an integer value greater than or equal to 2):");
input = new Scanner(System.in);
result = input.nextInt();
}
catch(NumberFormatException e)
{
System.out.println("Could not convert input to an integer");
System.out.println(e.getMessage());
System.out.println("Will use 10 as the default value");
}
catch(Exception e)
{
System.out.println("There was an error with System.in");
System.out.println(e.getMessage());
System.out.println("Will use 10 as the default value");
}
return result;
}//end of getInt
//Requires user to input a rhyme
//(does not necessarily have to rhyme)
private static ListInterface<String> getRhyme()
{
Scanner input;
Scanner rhymeWords;
String inString;
ListInterface<String> rhyme = new AList<String>();
try
{
input = new Scanner(System.in);
System.out.println("Please enter a rhyme:");
inString = input.nextLine().trim();
rhymeWords = new Scanner(inString);
while(rhymeWords.hasNext())
{
rhyme.add(rhymeWords.next());
}
}
catch(Exception e)
{
System.out.println("Input error!");
System.out.println(e.getMessage());
getRhyme();
}
//At least one word in the rhyme
if(rhyme.getLength() < 1)
{
System.out.println("You must enter at least one word in the rhyme");
getRhyme();
}
return (ListInterface<String>)rhyme;
}//end of getRhyme
//Loops through the rhyme with the players in the list,
//removing the selected player at the end of the rhyme.
//
//players = the list holding the players
//rhyme = the list holding the words of the rhyme
//startAt = a position to start the rhyme at
//
//the position of the player eliminated will be returned.
public static int doRhyme(ListInterface<Integer> players, ListInterface<String> rhyme, int startAt)
{
int numPlayers;
try
{
numPlayers = players.getLength();
while(numPlayers > 2)
{
for(startAt = 1; startAt < players.getLength(); startAt++)
{
for(startAt = 1; startAt < rhyme.getLength() + 1; startAt++)
{
System.out.println("Player " + players.getEntry(startAt) + ": " + rhyme.getEntry(startAt));
numPlayers = players.remove(--numPlayers);
}
}
}
}
catch(Exception e)
{
System.out.println("Rhyme performance error!");
}
return startAt;
}//end of doRhyme
}//end of class
列表的界面如下(以防有人想看我必须使用的方法)。
/**
An interface for the ADT list.
Entries in the list have positions that begin with 1.
*/
public interface ListInterface<T>
{
/** Adds a new entry to the end of this list.
Entries currently in the list are unaffected.
The list's size is increased by 1.
@param newEntry the object to be added as a new entry */
public void add(T newEntry);
/** Adds a new entry at a specified position within this list.
Entries originally at and above the specified position
are at the next higher position within the list.
The list's size is increased by 1.
@param newPosition an integer that specifies the desired
position of the new entry
@param newEntry the object to be added as a new entry
@return true if the addition is successful, or
false if newPosition < 1, or newPosition > getLength() + 1 */
public boolean add(int newPosition, T newEntry);
/** Removes the entry at a given position from this list.
Entries originally at positions higher than the given
position are at the next lower position within the list,
and the list's size is decreased by 1.
@param givenPosition an integer that indicates the position of
the entry to be removed
@return a reference to the removed entry or null, if either
the list was empty, givenPosition < 1, or
givenPosition > getLength() */
public T remove(int givenPosition);
/** Removes all entries from this list. */
public void clear();
/** Replaces the entry at a given position in this list.
@param givenPosition an integer that indicates the position of
the entry to be replaced
@param newEntry the object that will replace the entry at the
position givenPosition
@return true if the replacement occurs, or false if either the
list is empty, givenPosition < 1, or
givenPosition > getLength() */
public boolean replace(int givenPosition, T newEntry);
/** Retrieves the entry at a given position in this list.
@param givenPosition an integer that indicates the position of
the desired entry
@return a reference to the indicated entry or null, if either
the list is empty, givenPosition < 1, or
givenPosition > getLength() */
public T getEntry(int givenPosition);
/** Sees whether this list contains a given entry.
@param anEntry the object that is the desired entry
@return true if the list contains anEntry, or false if not */
public boolean contains(T anEntry);
/** Gets the length of this list.
@return the integer number of entries currently in the list */
public int getLength();
/** Sees whether this list is empty.
@return true if the list is empty, or false if not */
public boolean isEmpty();
/** Retrieves all entries that are in this list in the order in which
they occur in the list. */
public T[] toArray();
}
AList的定义如下:
/**
A class that implements the ADT list by using an array.
The list is unbounded.
*/
public class AList<T> implements ListInterface<T>
{
private T[] list; // array of list entries
private int numberOfEntries;
private static final int DEFAULT_INITIAL_CAPACITY = 25;
public AList()
{
this(DEFAULT_INITIAL_CAPACITY);
}//end of constructor
public AList(int initialCapacity)
{
numberOfEntries = 0;
T[] tempList = (T[])new Object[initialCapacity];
list = tempList;
}//end of constructor
public void add(T newEntry)
{
boolean isSuccessful = true;
if(!isFull())
{
//ensureCapacity();
list[numberOfEntries] = newEntry;
numberOfEntries++;
}
else
{
isSuccessful = false;
}
}//end of add
public boolean add(int newPosition, T newEntry)
{
boolean isSuccessful = true;
if(!isFull() && (newPosition >= 1) && (newPosition <= numberOfEntries + 1))
{
ensureCapacity();
makeRoom(newPosition);
list[newPosition - 1] = newEntry;
numberOfEntries++;
}
else
{
isSuccessful = false;
}
return isSuccessful;
}//end of add overload
public T remove(int givenPosition)
{
T result = null; // return value
if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
assert !isEmpty();
result = list[givenPosition - 1]; // get entry to be removed
// move subsequent entries towards entry to be removed,
// unless it is last in list
if(givenPosition < numberOfEntries)
{
removeGap(givenPosition);
}
numberOfEntries--;
} // end if
return result; // return reference to removed entry, or
// null if either list is empty or givenPosition
// is invalid
}//end of remove
public void clear()
{
for(int index = 0; index < numberOfEntries; index++)
{
list[index] = null;
}
numberOfEntries = 0;
}//end of clear
public boolean replace(int givenPosition, T newEntry)
{
boolean isSuccessful = true;
if(!isFull() && (givenPosition >= 1) && (givenPosition <= numberOfEntries)) // test catches empty list
{
assert !isEmpty();
list[givenPosition - 1] = newEntry;
}
else
{
isSuccessful = false;
}
return isSuccessful;
}//end of replace
public T getEntry(int givenPosition)
{
T result = null; // result to return
if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
assert !isEmpty();
result = list[givenPosition - 1];
}
return result;
}//end of getEntry
public boolean contains(T anEntry)
{
boolean found = false;
for(int index = 0; !found && (index < numberOfEntries); index++)
{
if(anEntry.equals(list[index]))
{
found = true;
}
}
return found;
}//end of contains
public int getLength()
{
return numberOfEntries;
}//end of getLength
public boolean isEmpty()
{
return numberOfEntries == 0;
}//end of isEmpty
public boolean isFull()
{
return numberOfEntries == list.length;
}
public T[] toArray()
{
T[] result = (T[])new Object[numberOfEntries];
for(int index = 0; index < numberOfEntries; index++)
{
result[index] = list[index];
}
return result;
}//end of toArray
public String toString()
// Returns a nicely formatted string that represents this list.
{
String listString = "";
for(int i = 0; i < numberOfEntries; i++)
{
listString = listString + " " + list[i];
}
return listString;
}//end of toString
// Doubles the size of the array list if it is full.
private void ensureCapacity()
{
if(numberOfEntries == list.length)
{
list = Arrays.copyOf(list, 2 * list.length);
}
}//end of ensureCapacity
// Makes room for a new entry at newPosition.
// Precondition: 1 <= newPosition <= numberOfEntries + 1;
// numberOfEntries is list's length before addition.
private void makeRoom(int newPosition)
{
assert(newPosition >= 1) && (newPosition <= numberOfEntries + 1);
int newIndex = newPosition - 1;
int lastIndex = numberOfEntries - 1;
// move each entry to next higher index, starting at end of
// list and continuing until the entry at newIndex is moved
for(int index = lastIndex; index >= newIndex; index--)
{
list[index + 1] = list[index];
}
}//end of makeRoom
// Shifts entries that are beyond the entry to be removed to the
// next lower position.
// Precondition: 1 <= givenPosition < numberOfEntries;
// numberOfEntries is list's length before removal.
private void removeGap(int givenPosition)
{
assert(givenPosition >= 1) && (givenPosition < numberOfEntries);
int removedIndex = givenPosition - 1;
int lastIndex = numberOfEntries - 1;
for(int index = removedIndex; index < lastIndex; index++)
{
list[index] = list[index + 1];
}
}//end of removeGap
}//end of class
最佳答案
也许这会有所帮助:
我看到有两种可能的情况:
案例一:
韵表大小大于等于人表大小。
操作 - 删除人员列表中的最后一个元素。
案例二:
人表的大小比韵表大。
操作 - 删除位于以下位置的人员列表中的元素:index = (person.size() % rhyme.size()) - 1
以下是应用程序的代码示例:
public static void main(String[] args){
//build lists and populate. Make sure that there are more
//players than rhymes so we can hit both cases.
ArrayList<Integer> player = new ArrayList<>();
ArrayList<Integer> rhyme = new ArrayList<>();
for(int i = 0; i < 10; i++){
if(i < 6){
rhyme.add(i);
}
player.add(i);
}
//play the game until we find a winner
while(player.size() > 1) {
int indexToRemove;
//case 1 followed by case 2
if (rhyme.size() >= player.size()) {
indexToRemove = player.size() - 1;
} else {
indexToRemove = (player.size() % rhyme.size()) - 1;
}
System.out.println(player.get(indexToRemove));
player.remove(indexToRemove);
}
System.out.println(player);
}
输出:
3
2
1
0
9
8
7
6
5
[4]
关于java : Loop through two ArrayLists without ListIterators using abstract data types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986234/
我认为这样的表达式会导致 Haskell 永远评估。但是 GHCi 和编译程序中的行为让我感到惊讶。 例如,在 GHCi 中,这些表达式一直阻塞到 I Control+C ,但不消耗 CPU。看起来像
就目前情况而言,这个问题不太适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、民意调查或扩展讨论。如果您觉得这个问题可以改进并可能重新开放,visit
如果可以的话,我想减少这段代码: class Alarm { internal static void isGreaterThanOrBelowValue(int min, int max,
我有以下问题: 我想创建一个批处理文件,循环访问一定数量的 IP 地址,以停止远程 PC 上的某个服务。 因为停止过程需要一些时间,所以我需要第二个循环来查询服务的状态并等待,直到服务达到“已停止”状
我已经完整地编写了“The Rust Programming Language”在线书籍中的程序,chapter 2 .我还进一步开发了它:通过添加一个简单的问题/响应,用户可以通过输入“y”再次玩游
这个人已经困扰了我一阵子了, 我们应该如何在集合中存储值或在for循环中映射? (let [s #{}] (for [ i (range 10) j (range 1
mov ecx, 16 looptop: . . . loop looptop 这个循环会执行多少次? 如果 ecx
我似乎无法找到一种在 Xtend 中表达以下内容而不诉诸 while 循环的好方法: for(int i = 0; i range(int stop) { range(0, stop) }
好吧,长话短说,我正在学习汇编,我正在尝试循环打印出 ascii 字符“0”-“9”。因此,我完成了我在示例中看到的所有基础知识,例如使用 pushad 和 popad 保存寄存器状态,分配堆栈空间,
我正在尝试为自己编写一个扑克计算器,我有一个 5 级深的 for 循环。 为此,我将 for 循环一个接一个地嵌套。我正在寻找一种方法来简单地使用一个循环(或函数),它可以告诉我想去多少层。对于这个例
我有一本包含约 150,000 个键的字典。没有重复的键。每个 key 的长度为 127 个字符,每个 key 在 1-11 个位置上有所不同(大多数差异发生在 key 的末尾)。每个键的值是一个唯一
我正在尝试编写一个 Lisp 程序来实现与点和方 block 非常相似的棋盘游戏,这意味着我有两个玩家相互竞争但可以连续移动。我正在尝试实现最简单的 minimax 算法来实现这一点,没有 alpha
下面是我实现的代码的简要说明。 for 循环的复杂度应该是 O(n)。我只是无法弄清楚内部 while 循环的时间复杂度。 int x,n; // Inputted by the user.
我目前正在尝试使用 html 分词器 https://godoc.org/golang.org/x/net/html . 所以我想做的是:从 url 获取所有链接,如果 url 包含特定字符串 ->
我有 32 个文件(以相同的模式命名,唯一的区别是下面写的 $sample 编号)我想分成 4 个文件夹。我正在尝试使用以下脚本来完成这项工作,但该脚本无法正常工作,有人可以帮我使用以下 shell
我必须根据 where 条件在我的内部表上做一个循环,但根据我的程序模式,必须在运行时修改 where 条件的字段。 我知道在 SELECT 语句中这是可能的,但是当我在循环中执行此操作时出现错误。
我正在学习关于kdb数据库的q。我担心q中没有循环。 我需要写一个算法,用像C这样的冗长程序在几个嵌套的for循环中编写。但是在q中,我被无法循环的事实所困扰。 仅举一个具体的例子(很多),我有一个简
我不明白为什么这段代码只循环一次然后退出? 在 Ghci 中,我只能回答第一个循环,然后似乎变量 cont 设置为 false 并且我没有提示回答。 结果是: *Main> testLoop1 td1
我正在 Racket 中运行 for 循环,对于列表中的每个对象,我想执行两件事:如果该项目满足条件,(1) 将其附加到我的新列表中,(2) 然后打印列表。但我不知道如何在 Racket 中执行此操作
我正在尝试使用 matlab 并行包中的 parfor 循环。我和这个人有类似的问题:MATLAB parfor slicing issue? 。输出矩阵似乎没有被识别为切片变量。在我的具体情况下,我
我是一名优秀的程序员,十分优秀!