精华内容
下载资源
问答
  • void main() { uchar i,AD;uint d; LCD_Initialise(); while(1) { AD=Get_AD_Result(); d= A/D *500.0*2/511.0; Disp_Buff1[11]d/100 +'0'; Disp_Buff1[13]=d/10%10 +'0'; Disp_Buff1[14]=d...
  • String.format()报错FormatFlagsConversionMismatchException,一开始以为是有参数为空了,设置为非null参数后,还是同样报错. import lombok.extern.slf4j.Slf4j; @Slf4j public class MainTest { public static ...

    String.format()报错 FormatFlagsConversionMismatchException,一开始以为是有参数为空了,设置为非null参数后,还是同样报错.

    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    public class MainTest {
        public static void main(String[] args) {
            String msg = String.format("接口请求失败,Id:s%,code:%s,msg:%s,sub_code:%s,sub_msg:%s","chsadfa","afsdfa","afafadf",null,"asdfaf");
            log.info(msg);
        }
    }

    Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = c, Flags = ,
        at java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4298)
        at java.util.Formatter$FormatSpecifier.checkBadFlags(Formatter.java:2997)
        at java.util.Formatter$FormatSpecifier.checkCharacter(Formatter.java:2974)
        at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2727)
        at java.util.Formatter.parse(Formatter.java:2560)
        at java.util.Formatter.format(Formatter.java:2501)
        at java.util.Formatter.format(Formatter.java:2455)
        at java.lang.String.format(String.java:2940)
        at com.rongsoft.demo.MainTest.main(MainTest.java:8)

    最后检查发现是%s 写成了 s%,异常类名FormatFlagsConversionMismatchException诚不余欺也.

     

    如果你写了5个%s,却只写了4个参数,这就会报错缺少格式化的参数(MissingFormatArgument)

    Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s'
        at java.util.Formatter.format(Formatter.java:2519)
        at java.util.Formatter.format(Formatter.java:2455)
        at java.lang.String.format(String.java:2940)
        at com.rongsoft.demo.MainTest.main(MainTest.java:8)

    所以参数要一一对应.

    展开全文
  • public static void main(String[] args) { List<String> alist = Arrays.asList(new String()); Iterator<String> iterator = alist.iterator(); while (iterator.hasNext()) { String str = ...

    以 Iterator.remove()为例子

    直接看代码

    public static void main(String[] args) {
       List<String> alist = Arrays.asList(new String());
       Iterator<String> iterator = alist.iterator();
       while (iterator.hasNext()) {
       String  str = iterator.next();
       //过滤list元素逻辑
       if (true) {
        iterator.remove();
          }
       }
    }

    错误为:

    Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractList.remove(AbstractList.java:161)
        at java.util.AbstractList$Itr.remove(AbstractList.java:374)

     

    改为正确方式

    public static void main(String[] args) {
       List<String> alist = new ArrayList<>();
       alist.add("test");
       Iterator<String> iterator = alist.iterator();
       while (iterator.hasNext()) {
          String str = iterator.next();
          //过滤list元素逻辑
          if (true) {
        iterator.remove();
           }
        }
    }

    两种方式区别

     List<String> alist = Arrays.asList(new String());

     List<String> alist = new ArrayList<>();
     alist.add("test");

     

     导致报错原因:

    首先分析两者之间获取的 Iterator 接口实例是否相同。(Iterator 本身是接口 默认remove方法为default void remove() { throw new UnsupportedOperationException("remove");} 如果抛异常也是实例覆盖remove方法抛出异常)

    Iterator<String> iterator = alist.iterator();

    很显然不同,一个是ArrayList 一个是 AbstractList

    Arrays.asList();方式

    可以看到Arrays 使用自己内部 静态 ArrayList 并不是 java.util.ArrayList

    看一下静态ArrayList继承 AbstractList内容 并无复写 iterator方法 所以调用  alist.iterator();是AbstractList 中iterator方法。
    第一张截图也得到了论证

    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;
    
        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }
    
        @Override
        public int size() {
            return a.length;
        }
    
        @Override
        public Object[] toArray() {
            return a.clone();
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }
    
        @Override
        public E get(int index) {
            return a[index];
        }
    
        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }
    
        @Override
        public int indexOf(Object o) {
            E[] a = this.a;
            if (o == null) {
                for (int i = 0; i < a.length; i++)
                    if (a[i] == null)
                        return i;
            } else {
                for (int i = 0; i < a.length; i++)
                    if (o.equals(a[i]))
                        return i;
            }
            return -1;
        }
    
        @Override
        public boolean contains(Object o) {
            return indexOf(o) != -1;
        }
    
        @Override
        public Spliterator<E> spliterator() {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }
    
        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            for (E e : a) {
                action.accept(e);
            }
        }
    
        @Override
        public void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            E[] a = this.a;
            for (int i = 0; i < a.length; i++) {
                a[i] = operator.apply(a[i]);
            }
        }
    
        @Override
        public void sort(Comparator<? super E> c) {
            Arrays.sort(a, c);
        }
    }

    具体iterator接口实例内容

    private class Itr implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0;
    
        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1;
    
        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;
    
        public boolean hasNext() {
            return cursor != size();
        }
    
        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
    
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
    
            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
    
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    这是重点后边我们比较一下remove方法有何不同

    new ArrayList<>();方式

    可以看到 ArrayList类 中使用匿名内部类实现了Iterator接口实例 并通过 iterator获取。

    具体实现Iterator接口内容

     

    最后比较一下remove方法不同,报错显示是remove

    Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractList.remove(AbstractList.java:161)
        at java.util.AbstractList$Itr.remove(AbstractList.java:374)

    首先看Arrays.asList()方式获取iterator 中remove方法。正好看错误提示 AbstractList:374行

    具体内容 AbstractList:161会直接抛出异常,看到这里我们就知道异常怎么来的啦

    new ArrayList<>();方式

    具体remove 方法: 

    总结一句话 ArrayList 重写了  AbstractList 抽象类的remove方法和add 方法支持操作实例,而Arrays创建的List实例没有重写 AbstractList中的remove方法和add方法。
    AbstractList 默认remove和add方法抛出UnsupportedOperationException异常

     

    建议:如果想要过滤List中元素,正好你使用的JDK8 可以考虑list.stream().filter() 进行过滤。这样就不用区分那种方式获取的List 实例了。(这种方式重新创建了一个List对象,会消耗一点堆空间)

    例子:

    public static void main(String[] args) {
        List<String> alist = new ArrayList<>();
        alist.add("test");
        alist.add("test1");
        List<String> alist1 = Arrays.asList("test1", "test2");
        System.out.println(alist);
        System.out.println(alist1);
        alist =alist.stream().filter(str->!str.equals("test1")).collect(Collectors.toList());
        alist1= alist1.stream().filter(str->!str.equals("test1")).collect(Collectors.toList());
        System.out.println(alist);
        System.out.println(alist1);
    }

    结果:

    [test, test1]
    [test1, test2]

    [test]
    [test2]

     

     

     

     

     

     

     

     

    展开全文
  • java list中删除元素用remove()报错的fail-fast机制原理以及解决方案现在有一个list,有6个元素,值分别是1、5、5、8、5、10,现需要删除值为5的元素第一种import java.util.ArrayList;import java.util.List;public ...

    java list中删除元素用remove()报错的fail-fast机制原理以及解决方案

    现在有一个list,有6个元素,值分别是1、5、5、8、5、10,现需要删除值为5的元素

    第一种

    import java.util.ArrayList;

    import java.util.List;

    public class ListRemove1 {

    public static void main(String args[]) {

    List list = new ArrayList();

    list.add(1);

    list.add(5);

    list.add(5);

    list.add(8);

    list.add(5);

    list.add(10);

    for (int j = 0; j < list.size(); j++) {

    if (list.get(j) == 5) {

    list.remove(j);

    }

    }

    outputList(list);

    }

    private static void outputList(List list) {

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

    System.out.print(list.get(i)+" ");

    }

    }

    }运行结果

    1    5    8    10

    这结果显然不是我们的预期,我们是希望删除List中所有为5的元素,但输出结果中却出现了5,这是因为在i等于1时,删除了List中的index为1的元素5,这时候list为[1,5,8,5,10], 但接下来,i递增后,等于2,在list.get(i)时,取出来的结果就成为了8了,也就是说随着list元素的删除,index是随之变化的,这就是其中的陷阱

    第二种

    import java.util.ArrayList;

    import java.util.Iterator;

    import java.util.List;

    public class ListRemove2 {

    public static void main(String args[]) {

    List list = new ArrayList();

    list.add(1);

    list.add(5);

    list.add(5);

    list.add(8);

    list.add(5);

    list.add(10);

    /*

    for (int i1 : list) {

    if (i1 == 5) {

    list.remove(i1);

    }

    }

    */

    Iterator iterator = list.iterator();

    while(iterator.hasNext()){

    if(iterator.next() == 5){

    list.remove(5);

    }

    }

    outputList(list);

    }

    private static void outputList(List list) {

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

    System.out.print(list.get(i)+" ");

    }

    }

    } 上面代码不管用增强for循环还是用Iterator遍历list,用list.remove()方法都报下面的错误:

    2e1caae12d646db32b54f756e6f110dc.png

    之所以报上面的错误是因为发生了fail-fast 事件。

    fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。

    例如:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。

    1.报ConcurrentModificationException异常的原因

    ConcurrentModificationException是在操作Iterator时抛出的异常,ArrayList的Iterator是在父类AbstractList.java中实现的,具体源码:

    public abstract class AbstractList extends AbstractCollection implements List {

    public Iterator iterator() {

    return new Itr();

    }

    private class Itr implements Iterator {

    /**

    * Index of element to be returned by subsequent call to next.

    */

    int cursor = 0;

    /**

    * Index of element returned by most recent call to next or

    * previous. Reset to -1 if this element is deleted by a call

    * to remove.

    */

    int lastRet = -1;

    /**

    * The modCount value that the iterator believes that the backing

    * List should have. If this expectation is violated, the iterator

    * has detected concurrent modification.

    */

    int expectedModCount = modCount;

    public boolean hasNext() {

    return cursor != size();

    }

    public E next() {

    checkForComodification();

    try {

    E next = get(cursor);

    lastRet = cursor++;

    return next;

    } catch (IndexOutOfBoundsException e) {

    checkForComodification();

    throw new NoSuchElementException();

    }

    }

    public void remove() {

    if (lastRet == -1)

    throw new IllegalStateException();

    checkForComodification();

    try {

    AbstractList.this.remove(lastRet);

    if (lastRet < cursor)

    cursor--;

    lastRet = -1;

    expectedModCount = modCount;

    } catch (IndexOutOfBoundsException e) {

    throw new ConcurrentModificationException();

    }

    }

    final void checkForComodification() {

    if (modCount != expectedModCount)

    throw new ConcurrentModificationException();

    }

    }

    protected transient int modCount = 0;

    }

    ArrayList中的remove()的实现

    public class ArrayList extends AbstractList implements List,

    RandomAccess, Cloneable, java.io.Serializable {

    public boolean remove(Object o) {

    if (o == null) {

    for (int index = 0; index < size; index++)

    if (elementData[index] == null) {

    fastRemove(index);

    return true;

    }

    } else {

    for (int index = 0; index < size; index++)

    if (o.equals(elementData[index])) {

    fastRemove(index);

    return true;

    }

    }

    return false;

    }

    /*

    * Private remove method that skips bounds checking and does not return

    * the value removed.

    */

    private void fastRemove(int index) {

    modCount++;

    int numMoved = size - index - 1;

    if (numMoved > 0)

    System.arraycopy(elementData, index + 1, elementData, index,

    numMoved);

    elementData[--size] = null; // Let gc do its work

    }

    }      无论是add()、remove(),还是clear(),只要涉及到修改集合中的元素个数时,都会改变modCount的值

    从源码中我们可以看出:

    1) Iterator  iterator = list.iterator();执行这语句时,此时Iterator中的expectedModCount = modCount(因为list有6个元素,所有该值为6),

    2)遍历到第二个元素即值为5的时候,list.remove(5);从ArrayList中的remove()实现中发现:modCount++;此时modCount的值为7

    3)在执行if(iterator.next() == 5)这语句即调用iterator的next()方法时,next()方法实现会调用checkForComodification();,该方法会执行 if (modCount != expectedModCount),即比较modCount和expectedModCount的值是否相等,此时expectedModCount的值为6而modCount的值为7,这两个值不相等,所以抛出

    throw new ConcurrentModificationException();这个异常

    第三种即解决方案:调用iterator的iterator.remove()方法,该方法的实现中,会执行expectedModCount = modCount;这个语句,即expectedModCount赋值为modCount;

    这样就保证expectedModCount 等于modCount,不会抛出ConcurrentModificationException()这个异常

    import java.util.ArrayList;

    import java.util.Iterator;

    import java.util.List;

    public class ListRemove4 {

    public static void main(String args[]) {

    List list = new ArrayList();

    list.add(1);

    list.add(5);

    list.add(5);

    list.add(8);

    list.add(5);

    list.add(10);

    Iterator iterator = list.iterator();

    while(iterator.hasNext()){

    if(iterator.next() == 5){

    iterator.remove();

    }

    }

    outputList(list);

    }

    private static void outputList(List list) {

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

    System.out.print(list.get(i)+" ");

    }

    }

    }运行结果:

    1    8    10

    展开全文
  • Scanner关闭close()报错

    千次阅读 2016-07-16 16:47:59
    最近同学遇到个问题问我,为什么我的程序里面在Scanner后加了close()之后程序会报错! 经过查阅以及实践之后算是弄清楚了到底出错在哪里... public static void main(String[] args){ Test test = new Test(); te

     最近同学遇到个问题问我,为什么我的程序里面在Scanner后加了close()之后程序会报错!

    经过查阅以及实践之后算是弄清楚了到底出错在哪里了。

    先看代码:

    import java.util.Scanner;
    public class Test {
     public static void main(String[] args){
      Test test = new Test();
      test.m1();
         System.out.println("System  qian");
      Scanner in = new Scanner(System.in);
         System.out.println("System  hou");
      String str = in.nextInt();//应该是这里出错
         System.out.println("next");
     
      System.out.println(str);
      
      System.out.println("close  qian");
      in.close();
      System.out.println("System  hou");
     }
     
     public void m1(){
      Scanner out = new Scanner(System.in);
      String str = out.nextLine();
      System.out.println(str);
      out.close();
     }
    }
    运行结果:4
    4
    System  qian
    System  hou
    Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)

    at Test.main(Test.java:9)

    至于为什么会在String str = in.nextLine();这里出错呢?

    原因是在m1()方法内已经执行过一次close()方法,close()方法一旦执行,则之后就算重新定义了Scanner s= new Scanner(System.in)也是不能够在使用next()之类的方法了。无论定义多上个Scanner对象,都是共享一个常量流的,(System.in这应该是一个常量流)一旦关闭了就不能够再使用。

    或者说System.in这个常量流被关闭了就无法再使用。

    那解决办法呢?

    就我这种菜鸟想到的解决办法就是在主函数类里面定义Scanner不管你这个类是否需要,只是为了在最后执行close(),然后在最后执行close(),其他的类按需要定义Scanner,但绝对不要执行close()。这样就能确保close()之执行一次,并且是在使用完之后在执行的。

    
    

    展开全文
  • public static void main(String[] args) throws IOException { String s = "Good Afternoon Doesn't IS a good body names NAMES 1,671,000 hy body"; Analyzer analyzer = new WhitespaceAnalyzer...
  • import java.util.ArrayList; ... //public static void main(String[] args) { ArrayList list1= new ArrayList(); ArrayList list2 = new ArrayList(); list1.add("汪峰"); }
  • mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));//错误行; mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView....
  • C语言 void main()出错

    2020-12-19 22:38:20
    c语言的标准语法是int main()void main()是未定义行为,程序能否正常运行由编译器决定。 CodeBlocks中,void main()就会报错。 程序设计中,我们应当使用正确的语法int main()
  • public static void main(String[] args) { TaMasterDao tmd=new TaMasterDao(); tmd.getById("1205020129"); } 我是使用的注解 import javax.persistence.Column; import javax.persistence....
  • at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at ...
  • int main(void) { int a[10]; srand((unsigned)time(NULL)); for (int i = 0; i < 10; i++) { a[i] = rand() % 100 + 1;//生成1——100的随机数 cout << a[i] << " ...
  • 【WCF】Open() 报错

    2019-10-10 10:17:19
    程序: static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(WcfServiceLib.Service1))) { if (host.State != CommunicationState.Opening) ...
  • Launcher我们知道很多语言的开始函数都是main函数,java也一样,那么我们可不可以更改java的入口函数呢?让他从我们自己的方法开始,当然可以,我们可以修改一下openjdk,改变程序入口的方法名,然后重新编译即可,...
  • <p>cls_task.finetune_and_eval() 报错: ---------------------------------------------------------------------------EnforceNotMet Traceback (most recent call last) in ----> 1 cls_task.finetune...
  • JavaSE-集合&Bug篇#使用Arrays调用asList(),添加元素报错“java.lang.UnsupportedOperationException”怎么回事? ☟看下面代码,写出打印结果,... public static void main(String[] args) { List<Strin...
  • public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"); //实例化一个Chrome浏览器的实例 ...
  • 作为Java大家庭中的集合类框架,List应该是平时开发中最...如:[java] view plaincopypublic class ListTest { public static void main(String[] args) { List&lt;Integer&gt; intList = n...
  • import java.io.BufferedReader; import java.io.InputStreamReader;... public static void main(String[] args){ // TODO Auto-generated method stub System.out.println("this is the first te.
  • 普通循环:利用index实现 增强型循环:通过迭代器实现 示例代码: ... public static void main(String[] args) { normalFor(getList()); //普通循环 iterator(getList()); //增强循环-...
  • 在运行指针时终端出现error: ‘::main’ must return ‘int’ void main()错误 源代码如下: #include<stdio.h> void main() { int a,*p,b,c,d,e; a=100; p=&a; /* (*&a) 先进行&a运算,得a的...
  • 普通循环:利用index实现增强型循环:通过迭代器实现示例代码:public class ArrayListTest {public static void main(String[] args) {normalFor(getList()); //普通循环iterator(getList()); //增强循环-迭代器...
  • public static void main(String[] args) { List<Integer> ases = new ArrayList(Arrays.asList( -1, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 1, 1, 1, 0, 0, 0, 0, -1, 1, 1, 1, 1, -1, -1, -1, -1,1)); ...
  • 首先导入两个jar包:commons-logging-1.1.1.jar和jmimemagic-0.1.1.jar...public static void main(String[] args) throws MagicParseException, MagicMatchNotFoundException, MagicException { File file = new Fi
  • public static void main(String[] args) { // 创建字符串对象 String s1 = "helloworld"; String s2 = "helloworld"; String s3 = "Helloworld"; // boolean equals(Object obj):比较字符串的内容是否...
  • public static void main(String [] args) { try { ServerSocket sersoc = null; try { sersoc = new ServerSocket(8399); } catch (Exception e) { // TODO: handle exception } Socket ...
  • code import java.net.URL;... public static void main(String[] args) { URL[] url = sun.misc.Launcher.getBootstrapClassPath().getURLs(); //sun.misc. for (URL value : url) { System.out.println(val
  • void main() { char *a = "-100.23"; float m = atof(a); printf("a = %.3f\n",m ); } ``` 运行结果为a=0.000 但是用atoi()的时候就好像没问题 ``` #include #include void main() { ...
  • 删除结点的时候使用了free(),运行后报错Trace/breakpoint trap** ```c //创建一个链表 PNODE creat_list(void) { int len;//用来临时存放用户输入的结点的个数 int val;//用来临时存放用户输入的...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,803
精华内容 1,521
关键字:

main()报错void