When I run my code I get an error that says
"DigitExtractor1.java:41: error: bad operand types for binary operator '%' oneDigit = (byte)(userInput % 10); ^ first type: String second type: int"
Im not sure where it went wrong. I thought when I casted the string to an int, it became an int? intCastFrmString = Integer.parseInt(userInput);
Here is the code:
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);
}
}
CodePudding user response:
You are using userInput, which has the type string, in oneDigit = (byte)(userInput % 10);, userInput /= 10;, and userInput != 0 instead of the int intCastFrmString.
CodePudding user response:
I suggest you to use br.readLine() and then convert it to int using type casting
