【问题标题】:Input String and int in the same line在同一行输入 String 和 int
【发布时间】:2015-10-17 12:31:50
【问题描述】:

如何在同一行输入Stringint?然后我想继续它以从我已经输入的 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);
    }
}

输入他人姓名和号码时出错。

我希望输出是这样的

姓名和号码:约翰 45
姓名和号码:保罗 30
姓名和电话号码:安迪 25

结果:约翰 45 岁

【问题讨论】:

    标签: java output user-input


    【解决方案1】:
    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);
    }
    

    希望这对你有用。

    【讨论】:

    • 如果你用" "分割输入,使用nextLine有什么意义?
    • 当“nextLine”方法返回被跳过的行时,sp​​lit 将输入值存储到两个不同的数组中。希望这能回答你的问题
    • 不,它没有回答我的问题,因为我仍然不知道您为什么更喜欢这种方法,而不是使用next,然后使用nextInt。当您已经知道" " 是您的分隔符时,让Scanner处理“拆分”。
    • 谢谢。这真的很有帮助
    • 更多代码?然后让我们比较一下你的方法:InputValue = in.nextLine(); String[] Value = InputValue.split(" "); name[x] = Value[0]; number[x] = Integer.parseInt(Value[1]); 和我的方法:name[x] = in.next(); number[x] = in.nextInt();
    【解决方案2】:
    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]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多