有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我可以在while循环中的圆括号内打印带有条件的内容吗?

我在玩这个代码

import java.util.Scanner;

class plus
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        do{
            System.out.print("Youe Value: ");
            long tobe = scan.nextLong();

            int total = 0;

            String parsed = String.valueOf(tobe);

            for(int i = 0; i < parsed.length(); i++) {
                total += Character.getNumericValue(parsed.charAt(i));
            }

            System.out.println("Your Result: "+ total);
        }
        while(scan.hasNextLong());
    }
}

输出应提示输入一个数字,然后进行处理并打印结果

然后再加上另一个输入,如果是integer(long)

但是while循环scan.hasnextLong中的条件接收输入本身并处理它,输出如下-

你的价值:你的结果:n

但预期的产出是这样的-

你的价值:m

您的结果:n

就像第一次一样托比在第一次之后似乎没有接受输入。它只是使用what-give-in循环条件来检查这是否是一个integer。在打印您的值之前,程序会更清楚地提示:,并在tobe中使用此值

所以我想打印while循环条件的内部

在这条线的某个地方,条件在圆括号内

while(scan.hasNextLong())

所以它可以像我想要的那样打印和提示


共 (3) 个答案

  1. # 1 楼答案

    我更改了您的代码,以便扫描仪获得String输入
    然后while条件检查它是否只包含数字。它通过调用输入上的.matches()来实现这一点,它尝试将输入字符串与正则表达式\d+匹配。此表达式匹配一个或多个数字的序列\d表示数字,+表示量词。您可以在像RegExr这样的网站上学习和使用正则表达式

        Scanner scan = new Scanner(System.in);
        String input;
    
        System.out.print("Your Value: ");
    
        while ((input = scan.nextLine()).matches("\\d+")){
    
            int total = 0;
    
            for(int i = 0; i < input.length(); i++) {
                total += Character.getNumericValue(input.charAt(i));
            }
    
            System.out.println("Your Result: "+ total);
            System.out.println("\nYour Value: ");
        }
    
        System.out.println("\nTHE END.");
        scan.close();
    
  2. # 2 楼答案

    while(scan.hasNextLong());替换为while(scan.hasNextLine());

  3. # 3 楼答案

    您需要在初始化之前打印一个值。如果使用print而不是println,则下一个输出将在同一行上

    public static void main(String[] args)
            {
    
              Scanner scan = new Scanner(System.in);
    
                do{
    
                    long tobe = scan.nextLong();
                    System.out.println("Your Value: " + tobe);
    
                    int total = 0;
    
                    String parsed = String.valueOf(tobe);
    
                    for(int i = 0; i < parsed.length(); i++) {
                        total += Character.getNumericValue(parsed.charAt(i));
                    }
    
                    System.out.println("Your Result: "+ total);
                }
                while(scan.hasNextLong());
            }