当前位置: 代码迷 >> J2SE >> 如何从键盘接收字符
  详细解决方案

如何从键盘接收字符

热度:34   发布时间:2016-04-24 13:55:32.0
怎么从键盘接收字符?
我是个菜鸟。问个简单的问题。怎么从键盘接收字符?
给个具体的例子。
谢谢各位了。

------解决方案--------------------
InputStream in = new InputStream(System.in);
...
------解决方案--------------------
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in) );//in是标准输入,就是键盘。
System.out.println(Stdin.readLine());//输出输入的字符


api里面有详细的介绍 scanner 1.5以后才有
------解决方案--------------------
try
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in) );//in是标准输入
}
catch(){ }
------解决方案--------------------
最简单的一个例子
class Test{
public static void main(String[] args){
String aStr = args[0];//接受键盘输入的第一个值
String bStr = args[1];//接受键盘输入的第二个值

int a = Integer.parseInt(aStr);
int b = Integer.parseInt(bStr);
int sum = a + b;
System.out.println(aStr + "+ " + bStr + "= " + sum);

}
}

运行时输入你需要的两个值,值之间需要打空格
例如:
java Test 1 2


------解决方案--------------------
接收十个数,输出最大 最小

package testFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MaxMin3 {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO 自動生成されたメソッド・スタブ
int i =1;
int s[] = new int[10];
while(i <=10) {
try {
String k;
switch(i) {
case 1: k = i + "st ";
case 2: k = i + "nd ";
case 3: k = i + "rd ";
default: k = i+ "th ";
}
System.out.println( "Please input the "+k+ " digit : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s[i-1] = Integer.parseInt(br.readLine());


} catch(IOException e){};

for(int m = 0; m <s.length - 1; m++) {
if (s[m]> s[m+1]) {
s[m] = s[m] + s[m+1];
s[m+1] = s[m] - s[m+1];
s[m] = s[m] - s[m+1];
}
System.out.println(s[9]);
System.out.println(s[0]);
}
}
}

}

------解决方案--------------------
package testFile;

import java.util.Arrays;
import java.util.Scanner;

public class MaxMin2 {
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < 10; i++ ){
String k;
switch(i+1) {
case 1: k = i + 1 + "st "; break;
case 2: k = i + 1 + "nd "; break;
case 3: k = i + 1 + "rd "; break;
case 10: k = "last "; break;
default: k = i + 1 + "th ";
}
System.out.println( "Please input the " + k + " digit: ");
Scanner in = new Scanner(System.in);
a[i] = in.nextInt();
// System.out.println(a[i]);
}

Arrays.sort(a);
for (int i = 0; i < 10 ; i++) {
System.out.print(a[i] + "\t ");
}
System.out.println();
System.out.println( "You 've input the largest is " + a[9]);
  相关解决方案