Java输入和输出语法(简单)

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

java input and output syntax (Simple)

问题

我有这个导入语句:

import java.util.List

输入:

public class solution{ List<String> words (String text, List<String> bannedWords) {//方法主体 } }

期望输出:字符串列表

我的代码:

HashSet<String> bannedWords = new HashSet<>();
HashMap<String, Integer> validWordsCount = new HashMap<>();

List<Character> result = List<>();

它显示以上行的符号找不到错误。我的语法是错误的(我认为它已经过时了,来自一个旧教程)。我可以将其写为Map而不是HashMap吗?

有人能告诉我输入和输出变量的正确语法吗?

英文:

I have this import statement:

import java.util.List

Input:

public class solution{ List<String> words (String text, List<String> bannedWords) {//BodyOfMethod } }

expected Output: list of strings

My code:

HashSet<String> bannedWords = new HashSet<>();
HashMap<String, Integer> validWordsCount = new HashMap<>();

List<Character> result = List<>();

It says error can't find symbol for the lines above. My syntax is wrong (I think it's out dated, from an old tutorial). Can I write it as Map instead of HashMap?

Can someone please tell me the correct syntax for the the variable to the input and output?

答案1

得分: 0

HashSet bannedWords = new HashSet<>();
HashMap<String, Integer> validWordsCount = new HashMap<>();

List result = new ArrayList<>();

通常,您会将变量类型定义为接口类型(SetMapList),并使用特定的实现类(HashSetHashMapArrayList)进行实例化。参见什么是“按接口编程”的含义?

所以这将是:

Set bannedWords = new HashSet<>();
Map<String, Integer> validWordsCount = new HashMap<>();

List result = new ArrayList<>();

所有这些类型都可以从java.util导入,例如:

import java.util.*;

英文:
HashSet&lt;String&gt; bannedWords = new HashSet&lt;&gt;();
HashMap&lt;String, Integer&gt; validWordsCount = new HashMap&lt;&gt;();

List&lt;Character&gt; result = List&lt;&gt;();

Typically you would type the variables as the interface types (Set, Map, List), and instantiate them with a particular implementation class (HashSet, HashMap, ArrayList). See What does it mean to “program to an interface”?

So this would be:

Set&lt;String&gt; bannedWords = new HashSet&lt;&gt;();
Map&lt;String, Integer&gt; validWordsCount = new HashMap&lt;&gt;();

List&lt;Character&gt; result = ArrayList&lt;&gt;();

All of these types can be imported from java.util, e.g.

import java.util.*;

huangapple
  • 本文由 发表于 2020年8月4日 16:32:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63243020.html
匿名

发表评论

匿名网友

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

确定