java如何输入一串分隔的数字串
在Java中,可以使用Scanner类来输入一串分隔的数字串。以下是一个示例代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(","); // 设置分隔符为逗号
while (scanner.hasNext()) {
int num = scanner.nextInt();
System.out.println("输入的数字是:" + num);
}
scanner.close();
}
}
在上述示例中,我们首先创建了一个Scanner对象,并将其与标准输入流(System.in)关联。然后,通过调用Scanner的useDelimiter()方法,设置分隔符为逗号。接下来,在一个while循环中,我们使用scanner.hasNext()方法来判断是否还有输入,如果有则使用scanner.nextInt()方法读取下一个整数,并将其输出。最后,记得关闭Scanner对象。
以上代码可以接受一串以逗号分隔的数字串作为输入,例如"1,2,3,4,5",并依次输出每个数字
AI 优化版
原文地址:https://www.cveoy.top/t/topic/iuta 著作权归作者所有。请勿转载和采集!