I want to separate int values that are provided via user input. For example, when entering 153 I want to extract each digit (3 then 5 then 1 or vice versa) and stick all of them into an int[].
So far I have used the modulus operator to extract the last digit, but I still need to extract all the previous digits so I can proceed to test whether the int given by the user is narcissistic or not.
The reason for doing this is so that I can test whether the user has inputted a narcissistic number. The program will return true or false depending on the input.
public class narc {
public static void main(String[] args){
Scanner myScan = new Scanner(System.in);
System.out.println("enter number: ");
int digit = myScan.nextInt();
String s1 = Integer.toString(digit);
System.out.println(narcNumber(digit));
}
public static boolean narcNumber(int number) {
System.out.println(number%10);
return false;
}
}
So far, narcNumber(num) only returns the last digit of the given number.
int[] split = new int[s1.length()];
for (int i = 0; i < split.length; i++) {
split[i] = Character.getNumericValue(s1.charAt(i));
}
split will contain all numbers of the input number.
If you still want to use modulus to get the digits :
List<Integer> digits = new ArrayList<Integer>();
while(inputNumber > 0) {
currentDigit = inputNumber % 10;
digits.add(currentDigit);
inputNumber = inputNumber / 10;
}
Related
I have some code that takes an integer and extracts the last 2 numbers and prints them. For example, if I input 10000001, 01 should be the printout/ output. The problem here is that for some reason the output of the program is 1. I am not sure why the output shows up as a single digit.
public class Main {
public static void main(String[] args) {
double num = 10000001;
double digit = num % 100;
System.out.println(digit);
}
}
Your problem is simple and has a simple answer.
In java int num = 1; is same as int num = 01; (both mean same 1 for the compiler) so when you are using % 100 with your number it returns 01 which is nothing but 1 for java as you are storing it to a double data type variable (actually when you use double in this line double digit = num % 100; it prints 1.0 , so you should use int here int digit = num % 100; to remove the decimal point).
So using int digit = num % 100; will work and give you desired results with all number except numbers having a 0 before a number.
To solve your problem completely you can use String class.
String str = num+""; //connverting int to string
String digit = str.substring(str.length()-2, str.length());
This is because your calculated value is "01". which while display java is considering it as "1". You can use padding but have to convert that integer to a string.
public static void main(String []args){
double num = 10000001;
int digit =(int) num%100;
String padding =String.format("%02d",digit);
System.out.println(padding);
}
Or If you are taking binary numbers better to use string and then displaying last two numbers using length() on string.
Another method you can try out is extracting the last two digits and printing as string.
int num = 10001;
int last_digit = num % 10; // extract the last digit
num /= 10; // modify the original number
int second_to_last_digit = num % 10; // extract second last digit
String str = String.valueOf(second_to_last_digit) + String.valueOf(last_digit); // convert and add strings
System.out.println(str); // print desired string
Using recursion I need to input a number and the console will print this number without its highest digit. If it's smaller than 10 it will return 0.
I already found the biggest digit but how can i remove it and print the number without it after?
This is the code for the biggest digit:
public static int remLastDigit(int n){
if(n==0)
return 0;
return Math.max(n%10, remLastDigit(n/10));
}
If i input 12345 i expect the output to be 1234. if i input 9 or less i expect the output to be 0.
Here is my solution:
// call this method
public static int removeLastDigit(int number) {
return removeLastDigitImpl(number, largestDigit(number));
}
private static int removeLastDigitImpl(int number, int largestDigit) {
if (number < 10) { // if the number is a single digit, decide what to do with it
if (number == largestDigit) {
return 0; // if it is the largest digit, remove it
} else {
return number; // if it is not, keep it
}
}
// handle the last digit of the number otherwise
if (number % 10 == largestDigit) {
// removing the digit
return removeLastDigitImpl(number / 10, largestDigit);
} else {
// not removing the digit
return removeLastDigitImpl(number / 10, largestDigit) * 10 + number % 10;
}
}
// this is the same as your attempt
private static int largestDigit(int n){
if(n==0)
return 0;
return Math.max(n%10, largestDigit(n/10));
}
Since you've already found the max digit nicely, here's how you can print the number without it.
public static void main(String[] args) {
printWithoutDigit(2349345, remLastDigit(2349345));
}
public static void printWithoutDigit(int number, int maxDigit) {
Integer.toString(number).chars().filter(digit -> Integer.valueOf(String.valueOf((char)digit))!=maxDigit).forEach(d -> System.out.print((char)d));
}
You could convert your number to a String, or more precisely to a char-array. Then, you can find out where in this array the biggest digit is, remove it and convert your char-array back to an integer.
This would roughly look like this:
int num = 12345; //the number from which you want to remove the biggest digit
char[] numC = String.valueOf(num).toCharArray();
int biggestDigit = 0;
int biggestDigitIndex = 0;
for (int i = 0; i < numC.length; i++) {
if (biggestDigit < Character.getNumericValue(numC[i])) {
biggestDigit = Character.getNumericValue(numC[i]);
biggestDigitIndex = i;
}
//Remove digit at index biggestDigitIndex from numC
//Convert numC back to int
}
Of course, you have to incorporate this into your recursion, which means returning the number you got after converting numC back to int and then feed this into your input parameter again. Also, of course you need to add a check if your number is < 9 in the beginning.
I am trying to find a way to identify 1 or 2 digit numbers in a string (there can't be any 3 digit numbers), add them together so they must be between 80 and 95.
For some reason, the code is not working, as it is always returning false, even when it should (in theory) return true.
ex. "Hi 57 how are you 30" returns false
Thank you in advance for your help!
("line" is the name of the String.)
public boolean isDig(){
int total=0;
int h;
int length = line.length();
for(h=0; h < length-1; h++) {
if (Character.isDigit(line.charAt(h))){
if (Character.isDigit(line.charAt(h+1))){
if (Character.isDigit(line.charAt(h+2))){
return false;
}
else {
total= total+(line.charAt(h)+line.charAt(h+1));
h++;
}
}
else {
total= total+(line.charAt(h));
}
}
if (total>=80 && total<=95){
return true;
}
else {
return false;
}
}
The main problem in the code is that line.charAt(h) isn't the numeric value of the digit at position h. It's the codepoint value, for example '0' is 48.
The easiest way to obtain the numeric value is Character.getNumericValue(line.charAt(h)), and similarly in other places.
You're also missing the multiplication by 10 of the first digit in the pair.
Assuming you know that the string is valid, it's easy enough just to add up any numbers in the string. The fact that they are 2 or 3 digits doesn't really matter from the perspective of obtaining the sum.
int total = 0;
for (int i = 0; i < line.length(); ) {
// Skip past non-digits.
while (i < line.length() && !Character.isDigit(line.charAt(i))) {
++i;
}
// Accumulate consecutive digits into a number.
int num = 0;
while (i < line.length() && Character.isDigit(line.charAt(i))) {
num = 10 * num + Character.getNumericValue(line.charAt(i));
}
// Add that number to the total.
total += num;
}
You should use a regex for this kind of parsing :
public class Example {
public static void main(String[] args) {
String input = "Hi 57 how are you 30";
System.out.println(process(input));
}
private static boolean process(String input) {
Pattern pattern = Pattern.compile(".*?(\\d+).*?(\\d+)");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
int one = Integer.parseInt(matcher.group(1));
int other = Integer.parseInt(matcher.group(2));
System.out.println(one);
System.out.println(other);
int total = one + other;
return total >= 80 && total <= 95;
}
return false;
}
}
Output :
57
30
true
One of the possible solution it to use Regual Expression.
public static boolean isValid(String str) {
// regular expression matches 1 or 2 digit number
Matcher matcher = Pattern.compile("(?<!\\d)\\d{1,2}(?!\\d)").matcher(str);
int sum = 0;
// iterate over all found digits and sum it
while (matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
return sum >= 80 && sum <= 95;
}
Let a java.util.Scanner do the work:
public boolean scan(String line) {
Scanner scanner = new Scanner(line);
scanner.useDelimiter("\\D+");
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum = a + b;
return sum >= 80 && sum <= 95;
}
The invocation of .useDelimiter("\\D+") delimits the string on a regular expression matching non-digit characters, so nextInt finds the next integer. You'll have to tweak it a bit if you want to pick up negative integers.
You could convert the String into an Array and test to see if each element in the String (separated by a space) is a Digit by testing the Integer.parseInt() method on each String element. Here is an example below:
public static boolean isDig(String theString) {
String[] theStringArray = theString.split(" ");
ArrayList<Integer> nums = new ArrayList<Integer>();
for(int x = 0; x < theStringArray.length; x++) {
String thisString = theStringArray[x];
try {
int num = Integer.parseInt(thisString);
nums.add(num);
}catch(NumberFormatException e) {
continue;
}
}
int total = 0;
for(int num: nums) {
total += num;
}
if(total >= 80 && total <= 95) {
return true;
}
else {
System.out.println(total);
return false;
}
}
We first split the original String into an Array based on the empty spaces. We then create an ArrayList that will add each digit in the String to it. We then create a for loop to look at each individual String in the Array and we set up a try-catch block. If we can covert the digit into an int using the Integer.parseInt() method, we will add it to the ArrayList. If not, we will catch the exception and continue the loop with a "continue" statement. Once we break out of the loop, we can create a variable called "total" and create another for loop in order to add each digit in the ArrayList to the total amount. If the total is greater than/equal to 80 and less than/equal to 95, we will return True, or else we will return false. Let's test the code:
String digitTest = "There is a digit here: 50 and a digit here 45";
System.out.println(isDig(digitTest));
The numbers 50 and 45 should equal 95 and our result is:
true
I tried to write a simple java program which counts how many odd digits there are inside a number (for example, for input "123" the program should return 2). The program instead returns all the digits of the given number. Any idea?
import java.util.*;
//Counts the number of odd digits in an int using recursion
public class OddCount{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
System.out.println("The number of odd digits is " + oddDigitCounter(n));
}
public static int oddDigitCounter(int number) {
int result = 0;
if(number<=10){
if(number%2==0)
result = 0;
else
result++;
}
else{
if(number%10!=0){
if((number%10)/2!=0)
result = 1 + oddDigitCounter(number/10);
else
result = 0 + oddDigitCounter(number/10);
}
else{
result = 0 + oddDigitCounter(number/10);
}
}
return result;
}
}
Here is a way to write your recursive method without all the unnecessary conditions.
public static int oddDigitCounter(int number) {
if (number==0) {
return 0;
}
return (number&1) + oddDigitCounter(number/10);
}
Using &1 instead of %2 allows it to work for negative numbers as well as positive ones.1
1 (number&1) is zero for an even number, and one for an odd number, and works regardless of whether the number is positive or negative. For instance, if number==-3 then (number%2)==-1, but (number&1)==1, which is what we want in this case.
Check your code, you are using / instead of % in this if condition:
if((number%10)/2!=0)
It should be:
if((number%10)%2!=0)
In oddDigitCounter() why don't you simply check digit by digit if it's an even or odd one and echo (store) the result?
Recursive approach: at first call you may pass to the function the entire number and then if the number is 1 digit long let the function do the check and return, otherwhise do the check against the 1st digit and pass the others again to the function itself.
Procedural approach: do a simple loop through the digits and do the checks.
You can use following sample:
import java.util.Scanner;
public class NumberOfOddDigist {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
countOdd(n);
System.out.println("The number of odd digits is " + count);
in.close();
}
public static void countOdd(int number) {
int remainder = number % 10;
int quotient = (number - remainder) / 10;
if (!(remainder % 2 == 0)) {
count++;
}
number = quotient;
if (number < 10) {
if (!(number % 2 == 0)) {
count++;
}
} else {
countOdd(number);
}
}
}
I am a cs student and i have an assignment that I'm not sure how to complete here is the prompt,
"Develop a Java console application for a simple game of guessing at a secret five-digit code (a random number from 10000 to 99999). When the user enters a guess at the code, the program outputs two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840 and the user guesses 83241, the digits 3 and 4 are in the correct positions. Thus, the program should respond with 2 (number of correct digits) and 7 (sum of the correct digits). Allow the user to guess until s/he gets it correct."
basically the part I am stuck on is how to find which numbers are correct numbers in common and add them together. Here is my code so far.
Random rand = new Random();
int secretNumber = rand.nextInt(99999 - 10000 + 1) + 10000;
System.out.println(secretNumber);
Scanner consoleScanner = new Scanner(System.in);
int guess;
do {
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
if (guess == secretNumber)
System.out.println("****HOORAY! You solved it. You are so smart****");
else if (guess > 99999 || guess < 10000)
System.out.println("Guess must be a 5-digit code between 10000 and 99999.\n");
} while (guess != secretNumber);
any help would be greatly appreciated.
You have a number. I'm going to call it blarg. Let's say blarg is a double.
You also have a number called input.
String blargString = Double.toString(blarg);
String inputString = Double.toString(input);
ArrayList<Integer[]> indexNumberList = new ArrayList<Integer[]>();
int n = 0;
for (char c : blargString.toCharArray()) {
n++;
if (c == inputString.toCharArray()[n]) {
Integer[] entry = new Integer[2];
entry[0] = n;
entry[1] = Character.getNumericValue(c);
indexNumberList.add(entry);
}
}
Now you have a list of Integer pairs. Do what you will with it. For each pair, entry[0] is the location in the number, the index, and entry[1] is the value.
Integer.toString(int) returns the string representation of an integer. You can compare the strings returned from Integer.toString(secretNumber) and Integer.toString(guess) character-by-character to determine which digits differ.
Here's how I'd go about solving that problem. My solution is quick but probably naive. Convert the number the user enters and your generated number to strings and then to two arrays of 5 bytes each. Scan through the arrays and compare two corresponding bytes at a time. Let the user know that the position of a digit was guessed correctly if two corresponding bytes are equal. Below, I show you how you can get the array of bytes you need.
byte[] a = Integer.toString(guess).getBytes();
byte[] b = Integer.toString(secretNumber).getBytes();
So you have 2 5-digit numbers that you need to compare.
I would recommend you to do this with a loop:
//Make copies so we can modify the value without changing
// the original ones.
int tempGuess = guess;
int tempSecret = secretNumber;
//Create variables for the output
int numCorrect = 0;
int sumCorrect = 0;
for(int i = 0; i < 5; i++) //for each of the digits
{
//Get the last digit of each number and remove it from the number:
int lastGuess = tempGuess%10;
tempGuess/=10;
int lastSecret = tempSecret%10;
tempSecret/=10;
//Compare both digits:
if(lastGuess == lastSecret)
{
//Found a match: Increas number of found by one
numCorrect++;
//Add value of digit to sum
sumCorrect += lastGuess;
}
}
//numCorrect now contains the number of matching digits
//sumCorrect now contains the sum of matchig digits
The solution can be address like:
define an counter for the coincidences and an accumulator for the adition of those
make a loop through the guess and compare char by char if the input at any given char match the random number, if so:
increase counter by one and add to the accumulator the integer value of the char.
Example:
final String s1 = Integer.toString(secretNumber);
final String s2 = Integer.toString(guess);
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
counter++;
acumm = Character.getNumericValue(s1.charAt(i));
}
}
System.out.println("There is/are " + counter + " coincidences");
System.out.println("The addition of those is: " + acumm);
you could use integers, use modulus and divide to get the digit you want.
53840 % 100000 / 10000 = 5
53840 % 10000 / 1000 = 3
loop and compare