For loop over contacts list is not executing.

huangapple go评论86阅读模式
英文:

For loop over contacts list is not executing

问题

我正在尝试创建一个联系人管理程序。我的计划是使用一个我创建的名为"Contact"的类的ArrayList。在存储了这些详细信息之后,我可以使用get方法获取姓名和号码。以下是主要代码部分。

package com.example.attemp1;

import java.util.ArrayList;
import java.util.Scanner;

public class hello {
    public static void main(String[] args) {
        while (true) {
            System.out.printf("1.管理联系人\n2.短信\n3.退出\n选择一个选项:");
            Scanner inp = new Scanner(System.in);
            ArrayList<Contact> contacts = new ArrayList<Contact>();
            int choice = inp.nextInt();
            int counter = 0, i;
            switch (choice) {
                case 1:
                    System.out.printf("\n1.显示所有联系人\n2.添加新联系人\n3.搜索联系人\n4.删除联系人\n5.返回上一项\n选择一个选项:");
                    Scanner inpt = new Scanner(System.in);
                    int opt = inpt.nextInt();
                    if (opt == 2) {
                        System.out.printf("输入姓名:");
                        Scanner nm = new Scanner(System.in);
                        String name = nm.next();
                        System.out.printf("输入号码:");
                        Scanner numb = new Scanner(System.in);
                        int num = numb.nextInt();
                        Contact c = new Contact(name, num);
                        counter++;
                        System.out.printf("计数器:%d\n", counter);
                        contacts.add(c);
                    } else if (opt == 1) {
                        i = 0;
                        for (i = 0; i < counter; i++) {
                            contacts.get(i).showname();
                            contacts.get(i).shownum();
                        }
                    }
                    break;
            }
        }
    }
}

下面是"Contact"类的代码。它具有两个方法"shownum"和"showname",这些方法应该帮助我显示姓名和号码。

package com.example.attemp1;

public class Contact {
    private String name;
    private int number;
    
    public Contact(String name, int number) {
        this.name = name;
        this.number = number;
    }
    
    public void showname() {
        System.out.printf("姓名:%s\t", this.name);
    }
    
    public void shownum() {
        System.out.printf("号码:%d\n", this.number);
    }
}

但问题是用于显示姓名和号码的循环不起作用。我的意思是循环甚至没有执行。

英文:

I am trying to create a contact management program.My plan is to use an arraylist of a class called contact that I have created. After storing the details,I can get the name and number using the get method.The below code is the main code.


import java.util.ArrayList;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
while (true)
{
System.out.printf(&quot;1.Manage contacts \n2.Message \n3.Quit \nSelect an option: &quot;);
Scanner inp=new Scanner(System.in);
ArrayList&lt;Contact&gt; contacts=new ArrayList&lt;Contact&gt;();
int choice=inp.nextInt();
int counter = 0,i;
switch (choice)
{
case 1:
System.out.printf(&quot;\n1.Show all contacts \n2.Add a new contact \n3.Search for a contact \n4.Delete a contact \n5.Go back to the previous item \nSelect an option: &quot;);
Scanner inpt=new Scanner(System.in);
int opt=inpt.nextInt();
if (opt==2) {
System.out.printf(&quot;Enter the name: &quot;);
Scanner nm=new Scanner(System.in);
String name=nm.next();
System.out.printf(&quot;Enter the number: &quot;);
Scanner numb=new Scanner(System.in);
int num=numb.nextInt();
Contact c=new Contact(name,num);
counter++;
System.out.printf(&quot;Counter: %d\n&quot;,counter);
contacts.add(c);
}
else if (opt==1){
i=0;
for (i=0;i&lt;counter;i++){
//System.out.printf(&quot;Inside\n&quot;); This line is to check if the loop is running 
//or not
contacts.get(i).showname();
contacts.get(i).shownum();
}
}
break;
}
}
}
}

The code for contact is below.It has the two methods shownum and showname which should help me display the name and number.

package com.example.attemp1;
public class Contact {
private String name;
private int number;
public Contact(String name,int number){
this.name=name;
this.number=number;
}
public void showname(){
System.out.printf(&quot;Name: %s\t&quot;,this.name);
}
public void shownum(){
System.out.printf(&quot;Number: %d\n&quot;,this.number);
}
}

But the problem is that for loop to show the name and number doesn't work.I mean that the loop isn't even executing.

答案1

得分: 2

你的ArrayList初始化放错了位置,这样每次接收新命令时都会创建一个新的ArrayList,而任何更改都会被删除。

为了解决这个问题,在while循环之前放置 ArrayList<Contact> contacts = new ArrayList<Contact>();

你还使用了一个计数器变量,你应该将其放在循环外,出于同样的原因,但是请注意,ArrayList类有一个叫做 size() 的方法,你可以用它来跟踪项目的数量,所以你不需要它。

每次想要扫描内容时,不需要创建一个新的scanner对象,你可以在while循环之外创建它。

Scanner sc = new Scanner(System.in);

在你的方法(在C中称为函数)开头不需要创建一个名为 i 的变量,这是在Java中使用for循环的常见方式:

for (int i = 0; i < counter; i++) {
    //System.out.printf("Inside\n"); 这行用于检查循环是否正在运行
    contacts.get(i).showname();
    contacts.get(i).shownum();
}
英文:

Your arraylist initialization is misplaced, so you are creating a new arraylist every time you receive a new command and any changes would be deleted.

To solve this, place ArrayList&lt;Contact&gt; contacts=new ArrayList&lt;Contact&gt;(); before the while loop.

You also use a counter variable which you should place outside the loop for the same reason, however note that the ArrayList class has a method called size() that you can use to keep track of the number of items, so you don't need it.

You do not need to create a new scanner object every time you want to scan something, you can create it once outside the while loop.

Scanner sc = new Scanner(System.in);

You do not need to create a variable named i at the start of your method (function in c) like the c language, this is the common way to use for loops in java:

                for (int i=0;i&lt;counter;i++){
//System.out.printf(&quot;Inside\n&quot;); This line is to check if the loop is running
//or not
contacts.get(i).showname();
contacts.get(i).shownum();
}

答案2

得分: 1

你在每次主循环迭代时重新初始化你的联系人列表和计数器。你应该将这些初始化操作移到while(true)之前。

例如:

public static void main(String[] args) {
    // 将初始化移到这里
    ArrayList<Contact> contacts = new ArrayList<Contact>();
    int counter = 0, i;
    while (true) {
        System.out.printf("1.管理联系人\n2.发送消息\n3.退出\n选择一个选项:");
        Scanner inp = new Scanner(System.in);
        // 从这里移除初始化
        // ArrayList<Contact> contacts = new ArrayList<Contact>();
        int choice = inp.nextInt();
        // 从这里移除初始化
        // int counter = 0, i;

然而一种更不容易出错的方式是将for循环改为

```java
for (Contact c : contacts)

这样你就不需要维护counter变量,可以完全将其移除。

英文:

You re-initialise your Contacts List and Counter at each iteration of the main loop.
You should move the initialisations before the while(true).

I.E.

   public static void main(String[] args) {
// MOVE INITIALISATION HERE
ArrayList&lt;Contact&gt; contacts=new ArrayList&lt;Contact&gt;();
int counter = 0,i;
while (true)
{
System.out.printf(&quot;1.Manage contacts \n2.Message \n3.Quit \nSelect an option: &quot;);
Scanner inp=new Scanner(System.in);
//REMOVE INIT FROM HERE
//ArrayList&lt;Contact&gt; contacts=new ArrayList&lt;Contact&gt;();
int choice=inp.nextInt();
//REMOVE INIT FROM HERE
//int counter = 0,i;

However a less error prone mode is to change the for loop too with

 for( Contact c:contacts)

so you don't have to mantain the counter variable and you can remove it completely

答案3

得分: 0

我尝试了你的代码,发现你的变量contactscounteri都放在while循环内部,每次迭代都会被重置。你应该像下面这样在while循环之前定义这些变量:

public class hello {
    public static void main(String[] args) {
        int counter = 0, i;
        ArrayList<Contact> contacts = new ArrayList<Contact>();
        while (true) {
            System.out.printf("1.管理联系人\n2.消息\n3.退出\n选择一个选项:");
            Scanner inp = new Scanner(System.in);

            int choice = inp.nextInt();

            switch (choice) {
                case 1:
                    System.out.printf("\n1.显示所有联系人\n2.添加新联系人\n3.搜索联系人\n4.删除联系人\n5.返回上一项\n选择一个选项:");
                    Scanner inpt = new Scanner(System.in);
                    int opt = inpt.nextInt();
                    if (opt == 2) {
                        System.out.printf("输入姓名:");
                        Scanner nm = new Scanner(System.in);
                        String name = nm.next();
                        System.out.printf("输入号码:");
                        Scanner numb = new Scanner(System.in);
                        int num = numb.nextInt();
                        Contact c = new Contact(name, num);
                        counter++;
                        System.out.printf("计数器:%d\n", counter);
                        contacts.add(c);
                    } else if (opt == 1) {
                        i = 0;
                        for (i = 0; i < counter; i++) {
                            //System.out.printf("Inside\n"); 这一行是用来检查循环是否运行
                            contacts.get(i).showname();
                            contacts.get(i).shownum();
                        }
                    }
                    break;

            }
        }
    }
}

我已经测试过了,它可以正常工作。祝好运!

英文:

I tried you code and your variables contacts, counter and i is placed inside the while loop which reset in each iteration. you should define those variables above your while loop like below:

public class hello {
public static void main(String[] args) {
int counter = 0,i;
ArrayList&lt;Contact&gt; contacts=new ArrayList&lt;Contact&gt;();
while (true)
{
System.out.printf(&quot;1.Manage contacts \n2.Message \n3.Quit \nSelect an option: &quot;);
Scanner inp=new Scanner(System.in);
int choice=inp.nextInt();
switch (choice)
{
case 1:
System.out.printf(&quot;\n1.Show all contacts \n2.Add a new contact \n3.Search for a contact \n4.Delete a contact \n5.Go back to the previous item \nSelect an option: &quot;);
Scanner inpt=new Scanner(System.in);
int opt=inpt.nextInt();
if (opt==2) {
System.out.printf(&quot;Enter the name: &quot;);
Scanner nm=new Scanner(System.in);
String name=nm.next();
System.out.printf(&quot;Enter the number: &quot;);
Scanner numb=new Scanner(System.in);
int num=numb.nextInt();
Contact c=new Contact(name,num);
counter++;
System.out.printf(&quot;Counter: %d\n&quot;,counter);
contacts.add(c);
}
else if (opt==1){
i=0;
for (i=0;i&lt;counter;i++){
//System.out.printf(&quot;Inside\n&quot;); This line is to check if the loop is running 
//or not
contacts.get(i).showname();
contacts.get(i).shownum();
}
}
break;
}
}
}
}

I tested it already it works. Cheers

huangapple
  • 本文由 发表于 2020年7月25日 16:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63086113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定