我和我的家庭作业的问题,我已经打了一堵墙。我是一个相当新的程序员,并通过嵌套的循环工作是混淆了我。我的程序运行不破坏;然而,当我进入一个重复的次数,每次我之后进入数量不添加到列表中。
的任务是:“。编写输入五个数字的应用程序,每10到100之间,包容每个号码被读取,显示它只是如果它不是已经看过了许多的副本提供的‘最坏情况’其中所有五个数字是不同的。使用尽可能最小的阵列来解决这个问题。在用户输入的每个新值之后显示完整组唯一值输入的“。
import java.util.Scanner;
public class Assignment1
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] array = new int[5];
int i = 0;
int input = 0;
boolean repeat = false;
int placeHolder = 0;
while(i < array.length) //While the number of inputs is less than the array length (5) Ask the user to input a number
{
System.out.printf("%s%d%s", "Please enter number", (i+1), ": ");
input = scan.nextInt();
if((input >= 10) && (input <= 100)) //Determine if the user input is in the range of 10-100
{
i++;
for(int x = 0; x < array.length; x++) //Determine if the user input is a repeat
{
if(input == array[x])
{
repeat = true;
System.out.println(input + " has already been entered.");
}
}
if(repeat == false) //If the user input isn't a duplicate - add it to the array
{
array[placeHolder] = input;
placeHolder++;
}
}
else
{
System.out.println("Invalid number! Please input a number between 10 and 100 (Inclusive)");
}
for(int y = 0; y < i; y++)
{
if(array[y] != 0)
{
System.out.print(array[y] + " ");
}
}
System.out.println();
}
}
}
你repeat
变量从未被重置了回false
,导致循环永远不会退出。
要解决,你可以在循环的每次迭代开始重新设置:
if((input >= 10) && (input <= 100)) {
repeat = false; // <--- added here
i++;
for(int x = 0; x < array.length; x++) {
if(input == array[x]){
repeat = true;
System.out.println(input + " has already been entered.");
}
}
if(repeat == false) {
array[placeHolder] = input;
placeHolder++;
}
}
话虽这么说,它可能不是这所学校分配的范围之内,但在未来,你可以使用Set
对象使代码短了很多。这个对象将不接受重复的值,所以你可以继续增加数到它,直到它是“全”。
一个不包含重复元素的collection
文档:https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
此外,你可以看看使用if(!repeat)
代替if(repeat==false)
。至少对我来说,与该编码风格+良好的布尔变量名的组合,它像是更容易理解。
在绝大多数情况下的“破发”出来的嵌套循环指示设计缺陷。并非在任何情况下,如此:
一)Java有一个休息的命令,做到了这一点:跳出循环/块的:
public static void main(String[] args){
for(;;){
while(){
break finished;
}
if(somecondition){
break finished;
}
}
finished:
// here we end up whenever we break out.
}
b)一个简单的返回这项工作:
public static void main(String[] args){
for(;;){
while(){
return;
}
// ...
if(somecondition){
return;
}
}
}
也许在一个额外的方法:
boolean worker(){
for(;;){
while(){
return true;
}
// ...
if(somecondition){
return false;
}
}
}
public static void main(String[] args){
boolean result = worker();
//do some finalizing or evaluate the result.
}
C)打出来的方案:
public static void main(String[] args){
for(;;){
while(){
System.extit(0); //success
}
// ...
if(somecondition){
System.extit(1); //some error
}
}
}
另一种方式是例外 - 这表明百达误差。
你选择什么样的依赖。
a)在解析器经常发现
b)是很常见的,如果有你交付(如果你编写程序的一部分,它作为天然的实际功能:一旦你有你返回的结果)
c)是常见的应用中,也许包裹,做一些额外的清理一个特殊出口方法。
在你的情况下,选择权在你,也许你重新考虑,如果你真的想打出来(文字听起来不像它)。
(注:这是一个直接和普遍的答案在标题的问题:“如何退出嵌套循环并完成程序”)
这是因为ü插入第一个重复的次数重复satys后真正的代码添加qazxsw POI的这个片段