java.util.NoSuchElementException:找不到行错误java

时间:2018-03-28 20:18:23

标签: java multithreading concurrency client-server java-threads

继续收到此错误 " java.util.NoSuchElementException:找不到行错误java" 并通过代码搜索了很多次,并且无法找到问题继承人我的文件可以有人帮忙吗? 我目前正在做这个任务,并试图将它从无线程转移到线程,并在此过程中出现了这个错误!!



This is the Client class

package Client;

import core.Email;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;


public class EmailClient {


    public static void main(String[] args) {
        try
        {
            // Step 1 (on consumer side) - Establish channel of communication
           Socket dataSocket = new Socket("localhost", EmailServiceDetails.LISTENING_PORT); 
           
           // Step 3) Build output and input objects
            OutputStream out = dataSocket.getOutputStream();
            PrintWriter output = new PrintWriter(new OutputStreamWriter(out));

            InputStream in = dataSocket.getInputStream();
            Scanner input = new Scanner(new InputStreamReader(in));
           
            Scanner keyboard = new Scanner(System.in);
            String message = "";
            while(!message.equals(EmailServiceDetails.END_SESSION))
            {
                displayMenu();
                int choice = getNumber(keyboard);
                String response = "";
                if(choice >=0 && choice < 3)
                {
                    switch (choice)
                    {
                        case 0:
                            message = EmailServiceDetails.END_SESSION;
                            
                            // Send message
                            output.println(message);
                            output.flush();
                            
                            response = input.nextLine();
                            if(response.equals(EmailServiceDetails.SESSION_TERMINATED))
                            {
                                System.out.println("Session ended.");
                            }
                            
                            break;
                        case 1:
                            message = sendEmail(keyboard);

                            // Send message
                            output.println(message);
                            output.flush();
                            
                            // Get response
                            response = input.nextLine();
                            
                            if(response.equals(EmailServiceDetails.SUCCESSFUL_ADD))
                            {
                                System.out.println("Email sent successfully");
                            }
                            else if(response.equals(EmailServiceDetails.UNSUCCESSFUL_ADD))
                            {
                                System.out.println("Sorry, the email could not be sent at this time.");
                            }
                            break;
                        case 2:
                            message = viewUnread(keyboard);
                            
                            // Send message
                            output.println(message);
                            output.flush();
                            
                            // Get response
                            response = input.nextLine();
                            if(response.equals(EmailServiceDetails.NO_UNREAD))
                            {
                                System.out.println("No unread mails found for that account.");
                            }
                            else
                            {
                                ArrayList<Email> unreadMails = EmailServiceDetails.parseEmailList(response);
                                System.out.println("Unread Emails:");
                                for(Email e: unreadMails)
                                {
                                    System.out.println(e);
                                }
                            }
                            break;
                    }
                    if(response.equals(EmailServiceDetails.UNRECOGNISED))
                    {
                        System.out.println("Sorry, that request cannot be recognised.");
                    }
                }
                else
                {
                    System.out.println("Please select an option from the menu");
                }
            }
            System.out.println("Thank you for using the Email system.");
            dataSocket.close();
        }catch(Exception e)
        {
            System.out.println("An error occurred: "  + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public static void displayMenu()
    {
        System.out.println("0) Exit");
        System.out.println("1) Send an email");
        System.out.println("2) View all unread mails");
    }
    
    public static int getNumber(Scanner keyboard)
    {
        boolean numberEntered = false;
        int number = 0;
        while(!numberEntered)
        {
            try{
                number = keyboard.nextInt();
                numberEntered = true;
            }
            catch(InputMismatchException e)
            {
                System.out.println("Please enter a number.");
                keyboard.nextLine();
            }
        }
        keyboard.nextLine();
        return number;
    }

    public static String sendEmail(Scanner keyboard)
    {
        System.out.println("Please enter the sender of this email:");
        String sender = keyboard.nextLine();
        
        // Get recipient information
        String anotherRecipient = "Y";
        ArrayList<String> recipients = new ArrayList();
        while(anotherRecipient.equalsIgnoreCase("Y"))
        {
            System.out.println("Enter the recipient's email address:");
            String recipient = keyboard.nextLine();
            recipients.add(recipient);
            
            System.out.println("Would you like to add another recipient? ('Y' for yes and 'N' for no)");
            anotherRecipient = keyboard.nextLine();
        }
        
        System.out.println("Please enter the email subject:");
        String subject = keyboard.nextLine();
        
        System.out.println("Please enter the message body:");
        String body = keyboard.nextLine();
        
        // Get attachment information
        ArrayList<String> attachments = new ArrayList();
        System.out.println("Would you like to enter an attachment ('Y' to add and 'N' to continue)");
        String anotherAttachment = keyboard.nextLine();
        
        while(anotherAttachment.equalsIgnoreCase("Y"))
        {
            System.out.println("Enter the attachment information:");
            String attachment = keyboard.nextLine();
            attachments.add(attachment);
            
            System.out.println("Would you like to add another attachment? ('Y' for yes and 'N' to Continue)");
            anotherAttachment = keyboard.nextLine();
        }
        
        long timestamp = new Date().getTime();
        String response = null;
        Email e = null;
        if(attachments.size() > 0)
        {
            e = new Email(sender, recipients, subject, body, timestamp, attachments);
        }
        else
        {
            e = new Email(sender, recipients, subject, body, timestamp);
        }
        
        response = EmailServiceDetails.ADD_MAIL + EmailServiceDetails.COMMAND_SEPARATOR + EmailServiceDetails.formatEmail(e);
        return response;
    }
  
    public static String viewUnread(Scanner keyboard)
    {
        
        System.out.println("Please enter the name of the email account you wish to see unread mail for:");
        String recipient = keyboard.nextLine();
        
        String response = EmailServiceDetails.VIEW_UNREAD + EmailServiceDetails.COMMAND_SEPARATOR + recipient;
        return response;
    }
}

--------------------------------------------------------------------------------
This is Server
---------------

package Server;
import Server.Commands.Command;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EmailServer {

    public static void main(String[] args) {
        try{
            // Set up a connection socket for other programs to connect to
            ServerSocket listeningSocket = new ServerSocket(EmailServiceDetails.LISTENING_PORT);
            
            // Create the list of emails to be stored and worked with
            EmailStore emails = new EmailStore();
            
            boolean continueRunning = true;
            int threadCount = 0;
            
            while(continueRunning)
            {
                // Step 2) wait for incoming connection and build communications link
                Socket dataSocket = listeningSocket.accept();
                
                threadCount++;
                System.out.println("The server has now accepted " + threadCount + " clients");

                // Step 3) Build thread 
                //         Thread should be given:
                //              1) a group to be stored in
                //              2) a name to be listed under
                //              3) a socket to communicate through
                //              4) Any extra information that should be shared
                
                EmailThread newClient = new EmailThread (emails, dataSocket.getInetAddress()+"", dataSocket,threadCount);
                
                newClient.start();
            }
            listeningSocket.close();
        }
        catch(Exception e)
        {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

--------------------------------------------------------------------------------
This is ServerThread
---------------

package Server;


import Server.Commands.Command;
import Server.EmailStore;
import core.EmailServiceDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

/**
 *
 * @author User
 */
public class EmailThread extends Thread {

    private Socket dataSocket;
    private Scanner input;
    private PrintWriter output;
    private int number;
    private EmailStore emails;

    public EmailThread(EmailStore emails,String name, Socket dataSocket, int number) {

   
        try {
            // Save the data socket used for communication between the thread and the Client
            this.dataSocket = dataSocket;
            // Save the id of the thread to identify output
// Save the id of the thread to identify output
            this.number = number;
            
            input = new Scanner(new InputStreamReader(this.dataSocket.getInputStream()));
            // Create the stream for writing to the Client
            output = new PrintWriter(this.dataSocket.getOutputStream(), true);
        } catch (IOException e) {
            System.out.println("An exception occurred while setting up connection links for a thread: " + e.getMessage());
        }
    }

    @Override
    public void run() {
        {
            String incomingMessage = "";
            String response;
            try {
                while (!incomingMessage.equals(EmailServiceDetails.END_SESSION)) {
                    // Wipe the response to make sure we never use an old value
                    response = null;

                    // take in information from the client
                    incomingMessage = input.nextLine();
                    System.out.println("Received message: " + incomingMessage);
                    // Break up information into components
                    String[] components = incomingMessage.split(EmailServiceDetails.COMMAND_SEPARATOR);

                    // Confirm that the command was correctly formatted 
                    // Did it include more than just the command text?
                    if (components.length > 1) {
                        CommandFactory factory = new CommandFactory();
                        // Figure out which command was sent by the client
                        // I.e. what does the client want to do?
                        Command command = factory.createCommand(components[0]);
                        
                        // Take the remaining text the client sent (i.e. all the information provided)
                        // and execute the requested action (e.g. store the new mail, get all sent mails etc)
                        response = command.createResponse(components[1], emails);
                    } else if (components[0].equals(EmailServiceDetails.END_SESSION)) {
                        response = EmailServiceDetails.SESSION_TERMINATED;
                    } else {
                        // If information was missing, set the response to inform the
                        // client that the command wasn't recognised
                        response = EmailServiceDetails.UNRECOGNISED;
                    }

                    // Send back the computed response
                    output.println(response);
                    output.flush();
                }
            } catch (Exception e) {
                System.out.println("An exception occurred while communicating with client #" + number + ": " + e.getMessage());
            } finally {
                try {
                    // Shut down connection
                    System.out.println("\n* Closing connection with client #" + number + "... *");
                    dataSocket.close();
                } catch (IOException e) {
                    System.out.println("Unable to disconnect: " + e.getMessage());
                    System.exit(1);
                }
            }
        }
    }

   
}

--------------------------------------------------------------------------------
This is EmailStore
---------------
package Server;

import core.Email;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class EmailStore 
{
    private ArrayList<Email> emailList = new ArrayList();
    
    public boolean addMail(Email newEmail)
    {
        return emailList.add(newEmail);
    }
    
    public boolean removeMail(Email mailToBeDeleted)
    {
        return emailList.remove(mailToBeDeleted);
    }
    
    public ArrayList<Email> findEmailByRecipient(String recipient)
    {
        ArrayList<Email> results = new ArrayList();
        
        results = (ArrayList<Email>) emailList.stream()
                // Find all emails whose recipients list contents the specified recipient
                .filter(email -> email.getRecipients().contains(recipient))
                // Collect the results back into a List (this does not return an ArrayList, so need to cast)
                .collect(Collectors.toList());
        
        return results;
    }
    
    public ArrayList<Email> findEmailBySender(String sender)
    {
        ArrayList<Email> results = new ArrayList();
        
        results = (ArrayList<Email>) emailList.stream()
                // Find all emails matching the specified sender
                .filter(email -> email.getSender().equals(sender))
                // Collect the results back into a List (this does not return an ArrayList, so need to cast)
                .collect(Collectors.toList());
        
        return results;
    }
    
    // Methods to mark emails as read
    // Provide a version that marks multiple mails as read AND a version that
    // marks a single email as read
    public void markMultipleAsRead(ArrayList<Email> emails)
    {
        for(Email e : emails)
        {
            markAsRead(e);
        }
    }
    
    public void markAsRead(Email e)
    {
        int index = emailList.indexOf(e);
        if(index != -1)
        {
            Email storedMail = emailList.get(index);
            storedMail.markAsRead(true);
        } 
    }
    
    // Methods to mark emails as spam
    // Provide a version that marks multiple mails as spam AND a version that
    // marks a single email as spam
    
    public void markAsSpam(Email e)
    {
        int index = emailList.indexOf(e);
        if(index != -1)
        {
            Email storedMail = emailList.get(index);
            storedMail.markAsSpam(true);
        } 
    }
    
    public void markMultipleAsSpam(ArrayList<Email> emails)
    {
        for(Email e : emails)
        {
            markAsSpam(e);
        }
    }
    
    public ArrayList<Email> findUnreadEmailByRecipient(String recipient)
    {
        ArrayList<Email> results = new ArrayList();
        
        results = (ArrayList<Email>) emailList.stream()
                // Find all emails whose recipients list contents the specified recipient AND the email is not unread
                .filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
                // Collect the results back into a List (this does not return an ArrayList, so need to cast)
                .collect(Collectors.toList());
        
        return results;
    }
}
-------
Help Appreciated

 - 


----------
&#13;
&#13;
&#13;

随着挫折程度的提高,帮助将非常受欢迎!!

1 个答案:

答案 0 :(得分:0)

这个答案是一个疯狂的猜测但是在主方法的switch语句的情况1中,你调用的是input.nextLine()扫描程序,它当时可能不包含信息。您可能必须首先使用hasNext()方法检查数据是否到达。

同样在收集电子邮件类的最后一种方法中,您不需要强制转换。可以这样做:

results = emailList.stream()
                   .filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
                   .collect(Collectors.toCollection(ArrayList::new));