7-6 jmu-Java-01入门-格式化输入输出与字符串

这篇文章展示了如何使用Java的Scanner类处理不同类型的输入(double,int,str,line),并对输入进行格式化输出,如保留小数位数、字符串连接和转换为大写。

###本题主要考察

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

###提示

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

    main

    ###输入说明:

  • 输入double,然后输入3个浮点数。输出:从左到右依次输出3个double(均保留2位小数输出,宽度为5),格式依次为:右侧填充空格,左侧填充空格,直接输出
  • 输入int,然后输入3个整数(以1个或多个空格分隔)。输出:将3个整数相加后输出。
  • 输入str,然后输入3个字符串。输出:去除空格,然后倒序输出3个字符。
  • 输入line,然后输入一行字符串。输出:转换成大写后输出。
  • 如果输入不是上面几个关键词,输出:输出other
  • 可使用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);
        String choice=new String();
        while(true){
            choice=sc.nextLine();
            if(choice.equals("double")){
                double[] d = new double[3];
                for (int i = 0; i < d.length; i++) {
                    d[i] = sc.nextDouble();
                }
                System.out.println("choice=double");
                System.out.printf("%-5.2f,%5.2f,%.2f\n", d[0], d[1], d[2]);
                sc.nextLine();
            }
            else if(choice.equals("int")){
                int[] a = new int[3];
                int sum = 0;
                for (int i = 0; i < a.length; i++) {
                    sum += sc.nextInt();
                }
                System.out.println("choice=int");
                System.out.println(sum);
                sc.nextLine();
            }
            else if(choice.equals("str")){
                String c1,c2,c3;
                c1=sc.next();
                c2=sc.next();
                c3=sc.next();
                System.out.println("choice="+choice);
                System.out.println(c3+c2+c1);
                sc.nextLine();
            }
            else if(choice.equals("line")){
                String s=sc.nextLine();
                System.out.println("choice="+choice);
                System.out.println(s.toUpperCase());
            }
            else{
                System.out.println("choice="+choice);
                System.out.println("other");
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值