踩坑合集
1、leetcode的题目很少涉及到Scanner的用法
(1)nextInt、nextLine以及next;
(2)对于多行输入的了解不足,与单行输入的差别仅在于nextLine
和单行一样还是使用语句Scanner xx = new Scanner( System.in );
(3) nextLine读取返回的是String类型,nextInt读取返回的是Int类型;
(4) next读取返回的也是String类型,只有nextLine不将空格看作是两个输入数据的间隔;
2、对冒泡排序不够熟悉
外层循环是自然计时器,控制内循环次数;
内循环用来控制比较次数,每次结束内循环,下次内循环迭代次数减少1;
3、对输出类型和形式的生疏
(1)System.out.println和System.out.print的差别,前者会换行
(2)输出方法
方法1、System.out.println(Arrays.toString(print).replace("[","").replace("]","").replace(",",""));
System.out.println(Array.toString());先将数组转化成字符串,然后输出
但是题目所需形式为A B C的单个字符串,所以需要更改形式
注:Array.toString()的形式为[A, B, C] ,逗号后有空格,因此只需要替换"[","]",","为空字符即可
方法2、for(int m : print)
{System.out.print(m+" ");}
注:int类型转String类型:
i + ""; //i 为 int类型,int+string型就是先将int型的i转为string然后跟上后面的空string
此处由于每次输出的是一个字符串,共有n个字符串,因此转化成string后,应该加上空格字符才能区分开n个整数值
方法3、 String str = "";
for(int j=0;j<n;j++)
{
str+= print[j]+" ";
}
System.out.println(str);
附代码:
import java.util.*;
public class Main{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int[] print = new int[n];
for(int i=0;i<n;i++)
{
print[i] = sc.nextInt();
}
//冒泡算法
int temp = 0;
for(int x=0;x<n-1;x++){
for(int y=0;y<n-1-x;y++)
{
if(print[y]>print[y+1]){
temp = print[y];
print[y] = print[y+1];
print[y+1] = temp;
}}}
//方法1 System.out.println(Arrays.toString(print).
// replace("[","").replace("]","").replace(",",""));
//方法2 for(int m : print) {System.out.print(m+" ");}
//方法3
String str = "";
for(int j=0;j<n;j++)
{
str+= print[j]+" ";
}
System.out.println(str);
}
}