04.scanner类

scanner类

创建

Scanner s = new Scanner(System.in);

方法

next:

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // next方式接收字符串
        System.out.println("next方式接收:");
        // 判断是否还有输入
        if (scan.hasNext()) {
            String str1 = scan.next();
            System.out.println("输入的数据为:" + str1);
        }
        scan.close();
    }

nextline:

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            System.out.println("输入的数据为:" + str2);
        }
        scan.close();
    }

区别:

next():

  • 1、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • 2、next() 不能得到带有空格的字符串。

nextLine():获得字符串

  • 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 2、可以获得空白。

nextDouble():获得double

nextFloat():获得float

循环计数

while (scan.hasNextDouble()) {//认为输入数字自动转换为double
            double x = scan.nextDouble();
            m = m + 1;
            sum = sum + x;
        }

while

while

dowhile(至少执行一次)

for

int[] number={1,2,4};
for(int x :number)
{

}
posted @ 2024-11-29 10:38  cookiesDing  阅读(40)  评论(0)    收藏  举报