当我运行客户端并输入一个数字时,它将作为字符串传递。但是它必须以整数形式传递。我该如何改变这一点?并且当用户输入“*”时程序结束时也从while(true)变为do。将字符串更改为整数
while (true){
System.out.print("Enter a number ");
String message = keyboard.nextLine();
out.writeUTF(message);
}
当我运行客户端并输入一个数字时,它将作为字符串传递。但是它必须以整数形式传递。我该如何改变这一点?并且当用户输入“*”时程序结束时也从while(true)变为do。将字符串更改为整数
while (true){
System.out.print("Enter a number ");
String message = keyboard.nextLine();
out.writeUTF(message);
}
使用int option = keyboard.nextInt();
在这里看到:if you want to know more
我该如何改变这一行? out.writeUTF(消息); – JanetKeelan
@JanetKeelan你想说什么? – osanger
我得到它排序。谢谢 – JanetKeelan
试试这个: Scanner.nextInt()
是给回一个整数...
例
final Scanner in = new Scanner(System.in);
int number = 0;
while(true){
System.out.print("Enter a number ");
number = in.nextInt();
out.writeUTF(number);
}
如果您需要循环执行此操作,直到用户输入特定的密钥(例如, “*”) 则:
final Scanner in = new Scanner(System.in);
String input = "";
do {
System.out.print("Enter a number ");
int numberParsed = 0;
input = in.nextLine();
try {
numberParsed = Integer.parseInt(input);
System.out.println(numberParsed);
out.writeUTF(numberParsed);
} catch (final NumberFormatException ex) {
System.err.println("That input could not be parsed to integer....");
}
} while (!input.equals("*"));
这个完美的作品。现在是否可以将其改为do,以便当用户输入“*”时程序停止运行? – JanetKeelan
是的,当然,但代码必须改变一点...看看更新请 –
我想象键盘是Scanner
类型的对象。
Scanner
有一个方法nextInt
来检索下一个整数。
String message = keyboard.nextLine();
int myInt = Integer.parseInt(message);
而不是使用nextLine
和writeUTF
,我会用nextInt
(和hasNextInt
让你终止输入与非int
:
否则,您可以使用方法Integer.parseInt
如下字符串转换为整数)与writeInt
。使用try-with-resources
和ByteArrayOutputStream
进行测试,可能看起来像
Scanner keyboard = new Scanner(System.in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(baos)) {
System.out.print("Enter a number ");
while (keyboard.hasNextInt()) {
int v = keyboard.nextInt();
out.writeInt(v);
System.out.print("Enter a number ");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(baos.toByteArray()));
什么是'keyboard'? – Aaron
http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java –