我正在使用 FindBugs 并且此错误不断生成:
依赖默认编码:
找到了一个方法调用,该方法将执行字节到字符串(或字符串到字节)的转换,并假定默认平台编码是合适的。这将导致应用程序行为因平台而异。使用替代 API 并明确指定字符集名称或字符集对象。
我认为这与扫描仪有关,这是我的代码:
package mystack;
import java.util.*;
public class MyStack {
private int maxSize;
private int[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new int[maxSize];
top = -1;
}
public void push(int j) {
stackArray[++top] = j;
}
public int pop() {
return stackArray[top--];
}
public int peek() {
return stackArray[top];
}
public int min() {
return stackArray[0];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
char end;
System.out.println("Please enter the size of the Stack: ");
int size=read.nextInt();
MyStack stack = new MyStack(size);
do{
if(stack.isEmpty()){
System.out.println("Please fill the Stack: (PUSH) \nBecause Stack is Empty.");
int add;
for(int i=0; i<size; i++)
{add=read.nextInt();
stack.push(add);}
}//End of if
else if(stack.isFull()){
System.out.println("Do you want to 1)POP 2)Know the Peek 3)Know the Min");
int option=read.nextInt();
if(option==1)
stack.pop();
else if (option==2)
System.out.println("The Peek= "+stack.peek());
else if (option==3)
System.out.println("The Min= "+stack.min());
else System.out.println("Error, Choose 1 or 2 or 3");
}//End of if
else
{ System.out.println("Do you want to 1)POP 2)Know the Peek 3)Know the Min 4)PUSH");
int option=read.nextInt();
if(option==1)
stack.pop();
else if (option==2)
System.out.println("The Peek= "+stack.peek());
else if (option==3)
System.out.println("The Min= "+stack.min());
else if(option==4)
{int add=read.nextInt();
stack.push(add);}
}//end else
System.out.print("Stack= ");
for(int i=0; i<=stack.top; i++)
{ System.out.print(stack.stackArray[i]+" ");}
System.out.println();
System.out.println();
System.out.println("Repeat? (e=exit)");
end=read.next().charAt(0);
System.out.println();
}while(end!='e');
System.out.println("End Of Program");
}//end main
}//end MyStack
Run Code Online (Sandbox Code Playgroud)
它显然是一个堆栈,工作正常。
FindBugs 担心默认字符编码。如果您使用的是 Windows,您的默认字符编码可能是“ISO-8859-1”。如果你在 Linux 下,它可能是“UTF-8”。如果您使用的是 MacOS,您可能正在使用“MacRoman”。您可能希望阅读有关字符集编码的更多信息,并通过单击链接了解有关Java 中可用编码的更多信息。
特别是,这一行使用默认平台编码从控制台读取文本:
Scanner read = new Scanner(System.in);
Run Code Online (Sandbox Code Playgroud)
为了确保代码在不同的环境中工作相同,FindBugs 建议您将其更改为
Scanner read = new Scanner(System.in, "UTF-8");
Run Code Online (Sandbox Code Playgroud)
(或您最喜欢的编码)。这将保证,给定使用编码“UTF-8”的输入文件,无论您在哪台机器上执行程序,它都会以相同的方式解析。
在您的情况下,您可以放心地忽略此警告,除非您有兴趣将文本文件输入到您的应用程序中。