PTA

您所在的位置:网站首页 使用scanner输入多个整数 PTA

PTA

2024-06-06 08:19| 来源: 网络整理| 查看: 265

题目要求:

###本题主要考察

使用Scanner处理输入使用System.out.printf进行格式化输出String常用方法与字符串常用操作 main

###输入说明:

输入double,然后输入3个浮点数。输出:从左到右依次输出3个double(均保留2位小数输出,宽度为5),格式依次为:右侧填充空格,左侧填充空格,直接输出输入int,然后输入3个整数(以1个或多个空格分隔)。输出:将3个整数相加后输出。输入str,然后输入3个字符串。输出:去除空格,然后倒序输出3个字符。输入line,然后输入一行字符串。输出:转换成大写后输出。如果输入不是上面几个关键词,输出:输出other。

###输出说明choice=你输入选项 该选项对应的输出内容

###提示

可使用line.split("\\s+");将以1个或多个空格分隔开的字符串分割并放入字符串数组。Scanner.nextLine与Scanner的其他next函数混用有可能出错。 输入样例: double 1.578 3.0 3.14259 line aaaaaaaaaa int 1 2 3 str 321 654 987 line dddddddddd end 输出样例: choice=double 1.58 , 3.00,3.14 choice=line AAAAAAAAAA choice=int 6 choice=str 987654321 choice=line DDDDDDDDDD choice=end other 代码: import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String type = sc.nextLine(); if(type.equals("double")){ double a = sc.nextDouble(); double b = sc.nextDouble(); double c = sc.nextDouble(); System.out.println("choice=double"); System.out.printf("%.2f , %.2f,%.2f\n",a,b,c); sc.nextLine(); }else if(type.equals("int")){ int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int sum = a+b+c; System.out.println("choice=int"); System.out.println(sum); sc.nextLine(); }else if(type.equals("str")){ String a = sc.nextLine(); String[] arr = a.split("\\s+"); System.out.println("choice=str"); for(int i = arr.length-1;i>=0;i--){ System.out.print(arr[i]); } System.out.println(); }else if(type.equals("line")){ String a = sc.nextLine(); String c = a.toUpperCase(); //a.toUpperCase()-->表示将a中的字符全都大写后赋给c System.out.println("choice=" + type); System.out.println(c); } else{ System.out.println("choice=" + type); System.out.println("other"); } } } }

type.equals("  ") ----> 用于字符串的比较

字符串的比较: 

        平时我们对数据进行比较时用的是 a==b;

        但我们比较字符串时发现问题,无论怎么样,代码不能进入判断体内。说明字符串不能使用“==”来判断是否相等。

        equals()方法是将两个字符串的 每个字符 是否相同进行逐一比较,若相同返回true反之返回false,对于字符的大小写也在检查范围内。

        equals()方法和==是两种不同的操作,equals()方法比较字符串对象中的字符,而“==”比较两个对象引用看它们是否引用相同的实例。

字符串比较的方法:

1.equals()方法

String str1 = "nine"; String str2 = "six"; str1.equals(str2);//false

2.equalslgnoreCase()方法

equalslgnoreCase()方法与equals()方法不同的点在于 equalslgnoreCase()方法在进行比较时不区分大小写,equals()方法区分大小写

 

String str1 = "niNe"; String str2 = "nine"; str1.equalsIgnoreCase(str2);//true

 String[] arr = a.split("\\s+") ---> 分割字符串并以数组的形式返回

分割字符串:

Java中提供split()方法来将字符串分割,其中不同写法有不同的意义:

其中,n可以替换为任意字符。

1.split(“ n ”): 以字符n为分隔线,分割后返回字符数组

String str1 = "nine"; String[] str2 = str1.split("n");//["i","e"]

2.split("\n"):以碰到的每个空格、换行符、回车为分隔线,如遇到连续多个空格、换行符、回车就会连续划分,分隔后返回字符数组;

3.split("\n+"):以空格、换行符、回车为分隔线,相邻的多个空格、换行符、回车仍然视为只有一个,分隔后返回字符数组。



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3