【发布时间】: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