首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无限循环被卡住,java中的代码出现问题

无限循环被卡住,java中的代码出现问题
EN

Stack Overflow用户
提问于 2020-03-13 23:55:43
回答 1查看 184关注 0票数 0

手头的任务是创建一个血液传输管理器应用程序,它可以有效地选择输血的捐赠者。

当应用程序启动时,它应该尝试打开两个文件:“donors.txt”和“recipients.txt”。如果其中一个文件丢失,程序应该通知问题并退出。这两个文件的格式都应该是:每一行都应该包含一个人的全名和他们的血型,用分号分隔。程序应该首先读取donors.txt,将每一行拆分为姓名和血型,并将结果数组作为新元素存储在捐赠者数组列表中。它还应该将列表打印在屏幕上,并检查每个人的血型是否有效。如果发现无效的血型,则不应将该条目添加到数组列表中,并且应通知用户哪个条目有问题。然后,应以类似的方式读取、处理和存储收件人(在收件人数组中)这是任务的一部分

这是我之前的代码,在更多地更新它以接近任务结束时,我发现代码停止了工作,我对它进行了调试,发现它陷入了无限循环,不确定如何修复它,或者是否有任何其他方法可以重写它以使其工作,可能不使用while循环

代码语言:javascript
运行
复制
package java_assigment_4;
import java.io.*;
import java.util.*;

public class java_assigment_4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner file_donors;
        Scanner file_recp;
        ArrayList list_donors = new ArrayList();
        ArrayList list_recp = new ArrayList();
        String blood_type = "o- o+ a- a+ b- b+ ab- ab+";


        try
        {
            file_donors = new Scanner(new FileReader("donors.text"));

            while (file_donors.hasNextLine())
            {
                list_donors.add(file_donors.nextLine());  // store donors  names & blood type in array list 

            }//end while

            file_donors.close();
         }//end try

        catch (FileNotFoundException e)
        {
            System.out.println("Error: " + e.getMessage());
        }//end catch


        try
        {
            file_recp = new Scanner(new FileReader("recipients.text"));

            while (file_recp.hasNextLine())
            {
                list_recp.add(file_recp.nextLine());  // store recipents names & blood type in array list 
            }//end while

            file_recp.close();
         }//end try

        catch (FileNotFoundException e)
        {
            System.out.println("Error: " + e.getMessage());
        }//end catch

        System.out.println("donors " + list_donors);
        System.out.println("\n");
        System.out.println("recipents " + list_recp);

       // for (int i=0;i<list_donors.size();i++) {
       // list_donors.contains(";"); // need a substring to store type after ; 
        }
    }
}

下面的代码是最新的代码,也是不起作用的代码

代码语言:javascript
运行
复制
public class java_assigment_4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner file_donors;
        Scanner file_recp;
        ArrayList<String> list_donors = new ArrayList<String>();
        ArrayList<String> list_recp = new ArrayList<String>(); 
        String [] blood_type = {"o-","o+","a-","a+","b-","b+","ab-","ab+"};

        try
        {
            file_donors = new Scanner(new FileReader("donors.txt"));

            while (file_donors.hasNextLine())
            {

                  for (int i=0;i<list_donors.size();i++) {

                        String donor=list_donors.get(i);
                        String type =donor.substring((donor.indexOf(";") + 1)); // look for ; and stores info after witch is the blood type into a substring so i can use for checking if vaild 
                        type=type.trim();



                         for (int z=0;z<blood_type.length;z++) {
                             if (type.equals(blood_type [z])) { compares the two lists
                                 list_donors.add(file_donors.nextLine());  // store donors names & blood if vaild type in array list 
                             }
                             else {
                                 System.out.println( "this person with blood;" + type + " is not valid ");
                                    }
                                }
                            }
                        }
                        file_donors.close();

                    } 

                    catch (FileNotFoundException e)
                    {
                        System.out.println("Error: " + e.getMessage());
                    }


        System.out.println("donors " + list_donors);

        try
        {
            file_recp = new Scanner(new FileReader("recipients.txt"));

            while (file_recp.hasNextLine())
            {
                  for (int i=0;i<list_recp.size();i++) {

                        String recp=list_recp.get(i);
                        String type =recp.substring((recp.indexOf(";") + 1));
                        type=type.trim();



                         for (int z=0;z<blood_type.length;z++) {
                             if (type.equals(blood_type [z])) { // compares the two lists 
                                 list_recp.add(file_recp.nextLine());  // store recp names & blood type if vaild in array list 
                             }
                             else {
                                 System.out.println( "this person with blood ;" + type + " is not valid ");
                                    }
                                }
                            } 
                        }

                        file_recp.close();
                     }

                    catch (FileNotFoundException e)
                    {
                        System.out.println("Error: " + e.getMessage());
                    }

       // System.out.println("donors " + list_donors);
       // System.out.println("\n");
       // System.out.println("recipents " + list_recp);


    }

}
EN

回答 1

Stack Overflow用户

发布于 2020-03-14 00:36:56

list_donors.size()将始终返回0,因为list_donors在开始时为空

因此代码永远不会调用file_donors.nextLine()

file_donors.hasNextLine()将永远是真的

代码语言:javascript
运行
复制
public class java_assigment_4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner file_donors;
        Scanner file_recp;
        ArrayList<String> list_donors = new ArrayList<String>();
        ArrayList<String> list_recp = new ArrayList<String>(); 
        String [] blood_type = {"o-","o+","a-","a+","b-","b+","ab-","ab+"};

        try
        {
            file_donors = new Scanner(new FileReader("donors.txt"));

            // file_donors.hasNextLine() always true in your code
            while (file_donors.hasNextLine())
            {
               // list_donors.size() will return 0, cause the list_donors is empty when it begins
               // so the code never enter this for and never call file_donors.nextLine()
               for (int i=0;i<list_donors.size();i++) {
               ...
               }
            }

你可以像这样做来避免这种情况

代码语言:javascript
运行
复制
  while (file_donors.hasNextLine())
  {
    string current_line = file_donors.hasNextLine();

使用一些代码进行更新以提供帮助

代码语言:javascript
运行
复制
import java.io.*;
import java.util.*;


public class Blood
{
  public static void main(String[] args)
  {
    ArrayList<String> list_donors = new ArrayList<String>();
    ArrayList<String> list_recp = new ArrayList<String>();

    System.out.println("Starting!");
    copyFromFile("/home/mitz/stackoverflow/java/Donors.txt", list_donors);
    System.out.println("imported "+ list_donors.size() + " registers");

    copyFromFile("/home/mitz/stackoverflow/java/Receptors.txt", list_recp);
    System.out.println("imported "+ list_recp.size() + " registers");
    System.out.println("Finished!");
  }

  public static void copyFromFile(String filename, ArrayList<String> listDestiny)
  {
    Scanner fileScanner;
    FileReader fileReader;
    try
    {
      fileReader = new FileReader(filename);
      fileScanner = new Scanner(fileReader);

      while (fileScanner.hasNextLine())
      {
        String currentLine = fileScanner.nextLine();
        String type = currentLine.substring((currentLine.indexOf(";") + 1));
        if(isValidBloodType(type))
        {
          listDestiny.add(currentLine);
          System.out.println("Imported: " + currentLine);
        }else{
          System.out.println("Invalid blood type!! Alien detected with blood type: " + type);
        }
      }

      fileScanner.close();
    }
    catch (FileNotFoundException e)
    {
      System.out.println("Arquivo não encontrado");
    }
  }

  public static Boolean isValidBloodType(String type)
  {
      String[] blood_type = {"o-", "o+", "a-", "a+", "b-", "b+", "ab-", "ab+"};
      return Arrays.asList(blood_type).contains(type);
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60673593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档