【问题标题】:How to return only digits from a scanned string? "incompatible types" error. java如何从扫描的字符串中只返回数字? “不兼容的类型”错误。爪哇
【发布时间】:2015-01-06 17:40:39
【问题描述】:

我尝试编译我的代码,但我的最后一个代码出现“不兼容错误”(否则)。我试图在该代码中说,“如果输入是数字和字母的混合,则只返回数字”,但它告诉我我所做的事情有问题,我无法弄清楚。

import java.util.*;
public class Pr8{
  public static void main(String[] args){
    Scanner scan = new Scanner (System.in);

    //Prompt the user for how many numbers are going to be entered

    System.out.print("* Please write how many numbers are going to be entered: ");
      if (!scan.hasNextInt())
        System.out.println("- Sorry your entery was not correct. The compiler except's digits only.");

      else {
        int a = scan.nextInt(); //a is the scanned number of the user request
        int[] n = new int[a];   //is an array to declare a variable as much as the user entered
        int num = 1;            //to show the sorting number of the string when printing

        //prompt the user to enter a mixture of digits and letters

        for (int i = 0; i < a; i++){
          System.out.print("* Please enter a string #" + num++ + ": ");
            if (scan.hasNextInt()){          //check if the input has only integers
              n[i] = scan.nextInt();
              System.out.println("- " + n[i] + " = " + n[i]);
            }//if
            else if (!scan.hasNextInt()){   //if the input was a mixture of digits and letters, return only the digits
              n[i] = scan.nextLine();
              System.out.println("- there is letters");
            }//else  
        }//for
      }//else if

  }//main
}//Pr8

【问题讨论】:

    标签: java incompatibility


    【解决方案1】:

    n[i] = scan.nextLine();

    您正在将一个字符串分配给一个 int 变量。你不能那样做。

    您可能应该显示一条错误消息,提示用户只输入数字。如果您希望向用户显示无效输入,请将scan.nextLine() 返回的String 存储在String 变量中。

    【讨论】:

    • 我知道,但我试图告诉编译器,如果用户输入了一个数字,则只打印该数字。否则,如果他混合打印了数字和字母,则只返回数字。怎么写?
    • @Bader 您可能需要一些正则表达式,但对我来说这不是一个好方法。假设用户错误地输入了 1O7 而不是 107。您会将其视为 17,而不是通知用户错误并要求输入有效。
    • 你是对的。但是,这就是我想要返回数字的原因,以便用户有机会查看他输入的数字。
    • 你知道它需要什么样的表达方式吗?
    • 程序应该如何工作的示例:要输入多少个数字? 4(由用户)47ab3 = 473 //// xxxA2zz = 2 //// x1x2x0x = 120 //// abcdefg1hijkl2MNOP = 12 ////
    【解决方案2】:

    用户Eran 是对的。无论如何,您的程序有点不干净。我建议你摆脱 cmets 并使用变量名来告诉读者它们应该包含什么。你想要的大概是这样的:

    import java.util.Scanner;
    
    public class Pr8 {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("How many numbers do you wish to enter?  ");
            while (!scanner.hasNextInt()) {
                System.err.print("Again, how many numbers?  ");
                scanner.next();
            }
            int numberCount = scanner.nextInt();
            int[] numbers = new int[numberCount];
            for (int i = 0; i < numberCount; i++) {
                String numberString;
                System.out.print("Please enter string #" + (i + 1) + " containing a number:  ");
                scanner.nextLine();
                while ((numberString = scanner.findInLine("[+-]?[0-9]+")) == null) {
                    System.err.print("Again, string #" + (i + 1) + " should contain a number:  ");
                    scanner.nextLine();
                }
                numbers[i] = Integer.parseInt(numberString);
                System.out.println("Number #" + (i + 1) + " found = " + numbers[i]);
            }
        }
    }
    

    控制台日志示例:

    How many numbers do you wish to enter?  weewdfsa
    Again, how many numbers?  324klj
    Again, how many numbers?  5
    Please enter string #1 containing a number:  23
    Number #1 found = 23
    Please enter string #2 containing a number:  sdfsdf
    Again, string #2 should contain a number:  werq
    Again, string #2 should contain a number:  sdf345df
    Number #2 found = 345
    Please enter string #3 containing a number:  -34ewr
    Number #3 found = -34
    Please enter string #4 containing a number:  wqweq+555
    Number #4 found = 555
    Please enter string #5 containing a number:  xxx-11yyy
    Number #5 found = -11
    

    【讨论】:

    • 你能看看我这里的问题吗:stackoverflow.com/questions/27181778/… ///// 我做的程序是9的补码处理java中的加减法,但是它有一些问题! !
    • 请您先接受并投票赞成这个答案,以便我们在切换到下一个问题之前关闭一个问题?
    • 但是你可以接受,因为你问了这个问题。
    【解决方案3】:

    下面是从字符串中过滤数字的示例。代码有点乱...希望你能明白。

    package strings;
    public class ScanNumbersOnly {
    
        public static void main(String[] args) {
            StringBuilder builder=new StringBuilder();
            int i=0,k=0,counter=0;
            String input="4 h5i dhfg 454hdkjfg dkjfhg iudhfg";
            System.out.println("String="+input);
            String spaceRemover[]=input.split(" ");
            for(String s:spaceRemover){
                builder.append(s);
            }
            input=builder.toString();
    
            char stringTocharacter[]=input.toCharArray();
            int stringarray[]=new int[stringTocharacter.length];
            for(char s:stringTocharacter){
                int charTonumericvalue=Character.getNumericValue(s);
                if(charTonumericvalue<=9){
                    stringarray[i]=charTonumericvalue;
                    counter++;
                }
                i++;
            }
            int finallist[]=new int[counter];
            for(int s:stringarray){
                if(s>0){
                    finallist[k]=s;
                    k++;
                }
            }
            System.out.print("After filtiring string=");
            for(int numberextractor:finallist){
                System.out.print(numberextractor);
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多