[华为面试题_ND2]运行错误请检查是否存在数组越界非法访问_野指针乱访问_空指针乱访问等情况_java_scanner_error
来源:互联网 发布:淘宝未按规定时间发货 编辑:程序博客网 时间:2024/06/10 18:53
问题描述:
在做华为面试题的时候,一个很简单的代码在本地编译可以通过,但是一提交就出问题。
检查了好久也没有发现是什么问题,然后去参考了别人的Accept才知道原来是scanner的问题。废话不多说,先把问题和代码贴上:
/*原始报错版本的代码*/import java.util.Scanner;public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int[] inputs= new int[10];//输入 int[] outputs=new int[10];//输出 int count=0; //计算输入元素的个数/*以下代码有问题,不能直接读取in,因为可能会有无效的输入,inputs中会存着其他无用的元素,之后访问这些元素的时候就会出错*/ int in = sc.nextInt(); while(in!=0&&count<10){ if(in<0||in>100) continue; inputs[count]=in; in = sc.nextInt(); count++; } int c=0; int n=0; for(int j=0;j<count;j++){ c=0; //count the times n=inputs[j]; while(n!=0){ c+=n/3; n=n/3+n%3; if(n==1) break; if(n==2) { c++; break; } } outputs[j]=c; //System.out.println(outputs[index]); } for(int i=0;i<count;i++){ System.out.println(outputs[i]); } }}
贴上Accept的代码:
import java.util.Scanner;public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int[] inputs= new int[10]; int[] outputs=new int[10]; int count=0; while(sc.hasNextInt()){ int in=sc.nextInt(); if(in<0||in>100) continue; inputs[count]=in; count++; } int c=0; int n=0; for(int j=0;j<count;j++){ c=0; //count the times n=inputs[j]; while(n!=0){ c+=n/3; n=n/3+n%3; if(n==1) break; if(n==2) { c++; break; } } outputs[j]=c; //System.out.println(outputs[index]); } for(int i=0;i<count;i++){ System.out.println(outputs[i]); } }}
在stack overflow上面看到了scanner的正确用法:
Scanner s = new Scanner(System.in);int choice = 0;if(s.hasNextInt()) { choice = s.nextInt();}s.close();//关闭scanner
总结:
1.学会从正确代码中寻找到自己的Bug,然后再对自己bug进行修改
2.中文搜索不到想要的内容,就用英文搜搜(讲道理最好用谷歌)
面试题网址:http://www.nowcoder.com/test/710802/summary–华为工程师编程题(牛客网)
参考:http://stackoverflow.com/questions/12832006/scanner-error-with-nextint
0 0
- [华为面试题_ND2]运行错误请检查是否存在数组越界非法访问_野指针乱访问_空指针乱访问等情况_java_scanner_error
- 牛客网 请检查是否存在数组越界非法访问,野指针乱访问,空指针乱访问等情况
- 请检查是否存在数组越界非法访问等情况
- 空指针访问错误
- 当字符串数组String[]为空时,通过下标访问时会越界,空指针异常
- C/C++常见指针错误 and 内存访问越界
- 用指针访问数组
- 字符数组指针访问
- 数组 指针访问
- 指针访问数组1
- 指针访问数组2
- 指针访问二维数组
- 指针访问数组
- 利用指针访问数组
- 指针访问多维数组
- 指针访问二维数组
- 指针访问多维数组
- C语言指针越界访问示例
- 使用结构体来优化shader的输入输出
- Mybatis学习记录(二)--Mybatis开发DAO方式
- HDU3068/Leetcode5 最长回文 (Manacher算法)
- 使用结构体来优化shader的输入输出
- 工作中的平时操作erlang相关
- [华为面试题_ND2]运行错误请检查是否存在数组越界非法访问_野指针乱访问_空指针乱访问等情况_java_scanner_error
- Host 'XXX' is not allowed to connect to this MySQL server 解决方案/如何开启MySQL的远程帐号
- shared_ptr不明确
- 【jQuery】OnSubmit中的Ajax判断
- 使用Properties和uniform来对着色器进行输入 附带介绍颜色插值混合的方法
- 浅谈XUtils第三方工具包的使用,主要用于客户端和服务器数据对接,适合初学者,
- 【Android UI】自定义TextView实现动态的文字闪动效果
- ruby 再mac下的安装
- Weblogic理解及配置