简体   繁体   English

多行输入java

[英]Multiple Input lines java

I want to write a program that reads this input: 我想编写一个读取此输入的程序:

 1 3 9 16 25 17 150312 0.5 13.8 2.4 

and it should output this: 它应该输出以下内容:

1.00,1.00
3.00,1.73
9.00,3.00
16.00,4.00
25.00,5.00
17.00,4.12
150312.00,387.70
0.50,0.71
13.80,3.71
2.40,1.55

My Code is this: 我的代码是这样的:

import java.util.Scanner;

public class SqrtTable {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in); 
        if(StdIn.isEmpty()==true) {
        }
        else {
            output(s);
        }
    }

    public static void output(Scanner s) {
        double a = StdIn.readDouble();
//      
        StdOut.printf("%.2f, %.2f", a, Math.sqrt(a));
//      System.out.println(a);
        StdIn.readLine();
    }
}

My Code only puts out the first line. 我的代码仅显示第一行。 What do I have to change? 我必须改变什么?

Try something like this: 尝试这样的事情:

Scanner sc = new Scanner(System.in);
String myString = sc.nextLine();
String[] flostr = myString.split(" ");
DecimalFormat df = new DecimalFormat("#.##");

for(String s : flostr){
   System.out.println(Float.parseFloat(s) +" ," + df.format(Math.sqrt(Float.parseFloat(s))));
}

Edit: Considering user input will be in different line, try something like: 编辑:考虑到用户输入将在不同的行中,请尝试如下操作:

public static void main(String args[]) {
   Scanner sc = new Scanner(System.in);
   List<String> list = new ArrayList<String>();

   System.out.println("Enter your numbers, enter 'end' when done: ");
   while(!sc.hasNext("end")){
       list.add(sc.next());
   }

   String[] flostr = list.toArray(new String[0]);
   for(String s : flostr){
       System.out.println(String.format("%.2f", Float.parseFloat(s)) +" ," + String.format("%.2f", (Math.sqrt(Float.parseFloat(s)))));
   }

}

By something like this 通过这样的事情

String[] splited = str.split("\\s+"); 
for(String s : splited){
System.out.println(s);
}

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

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