有 Java 编程相关的问题?

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

Java Eclipse TestMaxOfDigits

我想写一个程序,读取一个整数,并向用户显示该数字的最大位数。我的代码有什么问题

我在这里尝试了一些代码,但eclipse不允许! 正确的形式是什么?我应该如何将其更改为正确的形式

import java.util.Scanner;
public class TestMaxDigits {

    public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
        long n;
        long max = 0;   
            if(n%10>max){
                    max = n%10 ;
        System.out.println("max ="+max) ;


        }

    }

}

共 (2) 个答案

  1. # 1 楼答案

    您应该使用hasNextInt()nextInt()(或hasNextLong()nextLong())方法从Scanner类读取整数表单用户输入

    请尝试使用以下代码:

    public static void main( String[] args )
    {
    
        Scanner input = new Scanner( System.in );
        while( input.hasNextInt() )
        {
            int n = input.nextInt();
            long max = 0;
            if( n % 10 > max )
            {
                max = n % 10;
                System.out.println( "max =" + max );
    
            }
        }
    }
    

    你应该详细描述你到底想做什么

  2. # 2 楼答案

    它不起作用,因为逻辑上你的代码有缺陷

    public class TestMaxDigits {
    
        public static void main(String[] args) {
    
        Scanner input = new Scanner(System.in);
            long n;// you never read any input form the keyboard
            long max = 0;   
                if(n%10>max){//this check once for the condition and if found true
                //then assign the value to max in next step.
                        max = n%10 ;
            System.out.println("max ="+max) ;
    //but since number may have more than one digit which you never checked in your logic 
    
            }
    
        }
    
    }
    

    这里有一种方法

    public class Test {
    
        public static void main(String[] args)  {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Input number");
              int input=keyboard.nextInt();
              keyboard.close();
              int max=0;
              if(input>=0){
                  while(input!=0){
                      if(max<input%10)
                          max=input%10;
                        input=input/10;
                  }
              }else{
                  System.out.println("Invalid Input");
              }
    
               System.out.println(max);
    
            }
        }