简体   繁体   English

如何使用扫描器类编写程序应该只打印字符串值而不是整数值

[英]how to write a program using scanner class should print only string values but not int values

i want to write a program where scanner takes input of integers and strings at output it should not print integer value it has to print only string value..我想编写一个程序,其中扫描仪在输出时输入整数和字符串,它不应该打印整数值,它必须只打印字符串值..

input int value =6;输入整数值 =6;
input string value ="hello"输入字符串值 ="你好"

output=hello输出=你好

Scanner sc = new Scanner(System.in);
int x= sc.nextInt(); 
String v=sc.nextLine();
String v1 =sc.nextLine();
System.out.println(x+v1);

If you don't want to print integer values, you can write a custom Printer class with overloaded print and println methods for numeric types, like this:如果您不想打印整数值,您可以编写一个自定义 Printer 类,其中包含用于数字类型的重载printprintln方法,如下所示:

class MyPrinter{
  // constructors and stuff
  void print(int i){
    System.out.print('');
    // or you may as well just return;
  }
}

and if you dont want to print numbers at all you can also modify the function for String argument:如果您根本不想打印数字您还可以修改String参数的函数:

void print(String s){
  System.out.print(s.replaceAll("[0-9]+",""));
}

and this way, even if you concatenate numbers to your string, they won't be printed.这样,即使您将数字连接到您的字符串,它们也不会被打印出来。

If you just want to print values in string format, than you should write it like this.如果你只想以字符串格式打印值,那么你应该这样写。

System.out.println(v1);

Because x is integer and v1 is string.因为 x 是整数而 v1 是字符串。

If you print this:如果你打印这个:

System.out.println(x + v1);

This is going to automaticly convert x to string and print both values concatenated as string.这将自动将x转换为字符串并打印连接为字符串的两个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM