为什么java中的最后一个map元素不断重复

xpcnnkqh  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(231)

这个问题在这里已经有答案了

为什么我的arraylist包含添加到列表中的最后一项的n个副本(5个答案)
上个月关门了。
我在java代码块下面有一些问题:
产量是新德里的5倍。我想知道为什么其他Map元素没有列出,而最后一个元素不断重复?输出为:
`城市代码:del-->城市名称:新德里

City Code: DEL --> City Name: New Delhi
City Code: DEL --> City Name: New Delhi
City Code: DEL --> City Name: New Delhi
City Code: DEL --> City Name: New Delhi

例如,如果用户在第一次输入时给出3(表示元素的数量),那么程序只向数组获取2个元素,然后停止。
这个代码块永远不会停止,我怎样才能停止程序?
代码块:

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
public static void main(String[] args) {

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    Map<String, City> map = new HashMap<>();

    City moscow = new Moscow("Moscow", "MOW");
    map.put(moscow.getCityCode(), moscow);
    City london = new London("London", "LON");
    map.put(london.getCityCode(), london);
    City newyork = new NewYork("New York", "NYC");
    map.put(newyork.getCityCode(), newyork);
    City berlin = new Berlin("Berlin", "BER");
    map.put(berlin.getCityCode(), berlin);
    City newdelhi = new NewDelhi("New Delhi", "DEL");
    map.put(newdelhi.getCityCode(), newdelhi);

    List<City> cityByCode = new ArrayList<>(map.values());
    Collections.sort(cityByCode);
    for (int i = 0; i < cityByCode.size(); i++) {
        System.out.println("City Code: " + City.getCityCode() + " --> City Name: " + City.getCityName());
    }

    Scanner s = new Scanner(System.in);
    System.out.println("Select a minimum of three and a maximum of five cities listed above. First of all, please specify the number of cities you will choose: ");
    int length = s.nextInt();
    System.out.println("Please enter " + length + " city codes ");
    String[] myArray = new String[length];
    for (int i = 0; i < length; i++) {
        myArray[i] = s.nextLine();
    }

    for (String list : myArray) {
        switch (list) {
            case "MOW":
                executorService.execute(new SimpleThread(moscow));
                break;
            case "LON":
                executorService.execute(new SimpleThread(london));
                break;
            case "NYC":
                executorService.execute(new SimpleThread(newyork));
                break;
            case "BER":
                executorService.execute(new SimpleThread(berlin));
                break;
            case "DEL":
                executorService.execute(new SimpleThread(newdelhi));
                break;
        }
    }
}

}

ttp71kqs

ttp71kqs1#

您没有公开足够的代码来解决您的特定问题。但这里有一些提示和一些示例代码。
我对这方面不在行 Scanner ,但似乎你应该 … s.next(); 而不是 … s.nextLine(); .
总是在应用程序结束前关闭executor服务。否则,后台线程池可能会无限期地继续,就像僵尸一样?‍♂️.
使用现代java可以缩短代码。例如 Map.of , switch 表达式,并尝试使用资源。新的 record feature在合成getter时为不可变对象定义一个类, toString , equals ,和 hashCode 方法。但这只是语法,概念与原始代码中的相同。
通常最好从输入中去掉空白。
添加 default 给你的 switch 捕捉意外输入。
这里是一个完整的工作示例应用程序与代码接近您的原始。

package work.basil.example;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MapOut
{
    public static void main ( String[] args )
    {
        MapOut app = new MapOut();
        app.demo();
    }

    private void demo ( )
    {
        // ----------|  Data  |------------------------------------------
        record City( String name , String code )
        {
        }

        Map < String , City > map = Map.of(
                "MOW" , new City( "Moscow" , "MOW" ) ,
                "LON" , new City( "London" , "LON" ) ,
                "NYC" , new City( "New York" , "NYC" ) ,
                "BER" , new City( "Berlin" , "BER" ) ,
                "DEL" , new City( "New Delhi" , "DEL" )
        );
        System.out.println( "map = " + map );

        // ----------|  Action  |------------------------------------------
        ExecutorService executorService = null;
        try (
                Scanner scanner = new Scanner( System.in ) ;
        )
        {
            executorService = Executors.newFixedThreadPool( 5 );

            for ( String key : map.keySet() )
            {
                City city = map.get( key );
                System.out.println( "City code: " + city.code + " | name: " + city.name );
            }
            System.out.println( "Select a minimum of three and a maximum of five cities listed above. First of all, please specify the number of cities you will choose: " );
            int length = scanner.nextInt();
            System.out.println( "Please enter " + length + " city codes, pressing Return/Enter after each: " );
            List < String > inputCodes = new ArrayList <>( length );
            for ( int i = 0 ; i < length ; i++ )
            {
                String input = scanner.next();
                inputCodes.add( input.strip().trim() );
            }

            for ( String inputCode : inputCodes )
            {
                switch ( inputCode )
                {
                    case "MOW" -> executorService.submit( ( ) -> System.out.println( map.get( inputCode ).name ) );
                    case "LON" -> executorService.submit( ( ) -> System.out.println( map.get( inputCode ).name ) );
                    case "NYC" -> executorService.submit( ( ) -> System.out.println( map.get( inputCode ).name ) );
                    case "BER" -> executorService.submit( ( ) -> System.out.println( map.get( inputCode ).name ) );
                    case "DEL" -> executorService.submit( ( ) -> System.out.println( map.get( inputCode ).name ) );
                    default -> throw new IllegalStateException( "Expected city code: " + inputCode );
                }
            }
        }
        finally
        {
            if ( Objects.nonNull( executorService ) )
            {
                executorService.shutdown(); // Always shutdown your executor service. Otherwise it may continue indefinitely, like a zombie ?‍.
            }
        }
    }
}

正如目前所写的那样,做一个 switch 输入代码。我们可以放下枪 switch 用一条线 executorService.submit( ( ) -> System.out.println( map.get( inputCode ).name ) ); . 但我假设你脑子里还有其他特定于代码的逻辑,所以我把它忘了 switch 到位。
运行时,用户输入: 2 , MOW ,和 LON .

map = {MOW=City[name=Moscow, code=MOW], LON=City[name=London, code=LON], NYC=City[name=New York, code=NYC], DEL=City[name=New Delhi, code=DEL], BER=City[name=Berlin, code=BER]}
City code: MOW | name: Moscow
City code: LON | name: London
City code: NYC | name: New York
City code: DEL | name: New Delhi
City code: BER | name: Berlin
Select a minimum of three and a maximum of five cities listed above. First of all, please specify the number of cities you will choose: 
2
Please enter 2 city codes, pressing Return/Enter after each: 
MOW
LON
Moscow
London

相关问题