如何在Java中编写这个C++输入函数?

huangapple go评论66阅读模式
英文:

How would I write this C++ input function in Java?

问题

我正在努力弄清楚如何在Java中从控制台读取输入,以使其与以下C++代码完全相同:

Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
    int input = scanner.nextInt();
}

我基本上需要一次读取一个整数,只有当用户不再输入整数时才停止。我能够逐个读取整数,但无法弄清楚如何在用户输入空行后停止执行。谢谢!

英文:

I am trying to figure out how to read input from the console in Java that would behave exactly the same as the following C++ code:

while(cin >> input)

I essentially need to keep reading the console one integer at a time, and only stop when the user enters no more integers.I am able to read integers one at a time, but cannot figure out how to get it to stop executing once the user passes an empty line. Thanks!

答案1

得分: 1

      Scanner scanner = new Scanner(System.in);

      // 寻找下一个整数标记并打印
      // 循环整个扫描器
      while (scanner.hasNext()) {

         // 如果下一个是整数,则打印找到的整数
         if (scanner.hasNextInt()) {
            System.out.println("找到:" + scanner.nextInt());
         }
         // 如果没有找到整数,则打印“未找到:”和标记
         System.out.println("未找到:" + scanner.next());
      }
英文:
  Scanner scanner = new Scanner(System.in);

  // find the next int token and print it
  // loop for the whole scanner
  while (scanner.hasNext()) {

     // if the next is a int, print found and the int
     if (scanner.hasNextInt()) {
        System.out.println("Found :" + scanner.nextInt());
     }
     // if no int is found, print "Not Found:" and the token
     System.out.println("Not Found :" + scanner.next());
  }

答案2

得分: 0

import java.util.*;

class TextNum {

public static void main(String[] args) {

    int n;
    String s;

    Scanner in = new Scanner(System.in);  
    while (true) {
        s = in.nextLine();
        // 对此进行处理
        System.out.println("这是:" + s + ":");
        try {
            n = Integer.parseInt(s);               
        } catch (Exception e) {
            break;
        }
    }
   
}

}

英文:

You can use the Scanner nextLine() method and check for integers:

import java.util.*;

class TextNum {

public static void main(String[] args) {

    int n;
    String s;

     Scanner in = new Scanner(System.in);  
    while (true) {
        s = in.nextLine();
         //Do something with this
        System.out.println("This is :" + s + ":");
        try {
            n = Integer.parseInt(s);               
        } catch (Exception e) {
            break;
        }
    }
   
}

}

huangapple
  • 本文由 发表于 2020年9月11日 04:13:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63837066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定