gpt4 book ai didi

java - 我正在尝试检查句子中的数字。代码似乎在句子的第一个单词之后停止运行

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:00 25 4
gpt4 key购买 nike

import java.util.Scanner; 
public class DigitSumming {

public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
System.out.println ("Please enter a sentence: ");
String userSentence = in.next();

//writing for loop to check each character
int sum = 0;
int i;
for (i = 0; i < userSentence.length(); i++) {
if (Character.isDigit(userSentence.charAt(i))){
System.out.println("number: "+ userSentence.charAt(i));
}
}
}
}

这是我运行程序时得到的结果:

Please enter a sentence: 

7 ate 9

输出:

number: 7

最佳答案

您必须使用 nextLine() 而不仅仅是 next()

更正的代码片段:

import java.util.Scanner; 
public class DigitSumming {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println ("Please enter a sentence: ");
/* Corrected Here */
String userSentence = in.nextLine();

//writing for loop to check each character
int sum = 0, i;
for (i = 0; i < userSentence.length(); i++) {
if (Character.isDigit(userSentence.charAt(i))){
System.out.println("number: "+ userSentence.charAt(i));
}
}
}
}

输入:

7 ate 9

输出:

number: 7
number: 9

关于java - 我正在尝试检查句子中的数字。代码似乎在句子的第一个单词之后停止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36312910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com