【问题标题】:Why did my string not cast into an int? I used Integer.parseInt()为什么我的字符串没有转换成 int?我使用了 Integer.parseInt()
【发布时间】:2022-02-02 03:02:17
【问题描述】:

当我运行我的代码时,我得到一个错误提示

"DigitExtractor1.java:41: 错误:二元运算符 '%' 的操作数类型错误 oneDigit = (byte)(userInput % 10); ^ 第一种:字符串 第二种:int"

我不确定哪里出错了。我想当我将字符串转换为int时,它变成了一个int? intCastFrmString = Integer.parseInt(userInput);

代码如下:

import java.util.Scanner;

public class DigitExtractor1{
   
   public static void main(String[]args){
      
      //variables
      final int PERIOD_UNICODE = (int) ('.');
      String userInput;
      int intCastFrmString;
      byte oneDigit;
      boolean validInput;
      
      //scanner object
      Scanner x = new Scanner(System.in);
      
      System.out.print("Enter an integer: ");
      userInput = x.nextLine();
      
      //loop to collect input from the user
      if (userInput.indexOf(PERIOD_UNICODE) != -1){
         validInput = false;
         System.out.println("Input is a floating pt number; try again: ");
         
      }else{
         validInput = true;
         System.out.println(userInput + " is a vlaid integer");
         //string to an int
         intCastFrmString = Integer.parseInt(userInput);
      }
      
      //loop to extract and display the digits in int
      System.out.println("Extracted digits of: " + userInput);
      do{
         //determine rightmost digit
         oneDigit = (byte)(userInput % 10);
         
         //if oneDig is neg, display purposes, take abs val
         if(oneDigit < 0)
            oneDigit *= -1;
            
         //display digit
         System.out.println(oneDigit);
         
         //reduce the int by factor of ten
         userInput /= 10;
      }while(userInput != 0);

   }
}

【问题讨论】:

  • 您需要在计算中使用您的转换值:oneDigit = (byte)(intCastFrmString % 10); 这是因为您在计算中使用了字符串输入。
  • javaranch.com 是一个非常适合初学者的网站

标签: java string casting integer


【解决方案1】:

您正在使用 oneDigit = (byte)(userInput % 10);userInput /= 10;userInput != 0 中的 userInput,它的类型为 string,而不是 int intCastFromString。

【讨论】:

  • 在将它们更改为之后,它说 intCastFrmString 可能尚未初始化?我是否将铸件移到我所在的 if 语句之外?
【解决方案2】:

我建议你使用 br.readLine() 然后使用类型转换将其转换为 int

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2020-04-12
  • 2017-06-11
  • 2014-10-20
  • 1970-01-01
相关资源
最近更新 更多