java 在同一行输入 String 和 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33186650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input String and int in the same line
提问by nanang
How can I input a String
and an int
in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
如何在同一行中输入 aString
和 an int
?然后我想继续它以从我已经输入的 int 中获取最大数字:这是我到目前为止编写的代码。
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
当我输入其他人的姓名和号码时出现错误。
I expect the output will be like this
我希望输出是这样的
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25Result: John 45
姓名和号码:约翰 45
姓名和号码:保罗 30
姓名和号码:安迪 25结果:约翰福音 45
回答by GMB
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
希望这对你有用。
回答by AbA2L
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);