首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中有没有与C的scanf等价的方法?

在Java中有没有与C的scanf等价的方法?
EN

Stack Overflow用户
提问于 2013-06-07 17:55:30
回答 6查看 127.4K关注 0票数 34

Java具有与format strings in other languages非常相似的format strings概念。它在String#format()等JDK方法中用于输出转换。

我想知道在Java中是否有类似于C's scanf的输入转换方法?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-06-07 18:01:24

看看this site,它解释了两种从java控制台读取数据的方法,分别是使用Scanner或System.in中的经典InputStreamReader

以下代码取自引用的网站:

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

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

致以问候。

票数 22
EN

Stack Overflow用户

发布于 2013-06-07 17:58:08

在标准Java中没有纯粹的scanf替代,但是您可以使用java.util.Scanner来解决使用scanf解决的相同问题。

票数 12
EN

Stack Overflow用户

发布于 2019-10-22 22:22:50

不是等效项,但您可以使用Scanner和模式来解析由空格分隔的三个非负数的行,例如:

71 5796 2489
88 1136 5298
42 420 842

下面是使用findAll的代码

new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
        .forEach(result -> {
            int fst = Integer.parseInt(result.group(1));
            int snd = Integer.parseInt(result.group(2));
            int third = Integer.parseInt(result.group(3));
            int sum = fst + snd + third;
            System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
        });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16981232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档