OK so I am writing a program that compares the number entered by a user to a computer generated number. Each number is 3 digits. What I'd like to know how to do is compare these integers. So for example if the last two digits of the three digit numbers are the same it will run a block of code. I'm not completely sure how to go about this. Any youtube videos or any links would be much appreciated. I would rather understand than get an answer to my code.
The fastet way would be: Convert the Integer to a String and then split the string at each char. Then you have an Char Array with each digit and you can compare them like whatever you want.
int number = 324;
String number_string = String.valueOf(number); //converts integer to string
char[] digits = number_string.toCharArray(); //converts string to char array
if(digits[2] == 4){ //checks if 3rd digit of the char array is 4
//do something
}
You can get last two digit by modulo(%) operator.when you modulo three digit number by 100 it return last two digit and compare these digit in if condition like,
int num=154; //number of three digit
int rem=num%100;//modulo by 100 return remainder
if(rem==54){ //checking condition
//code
}
else{
//code
}
I suppose that the number entered is a String so first you want to convert it to an integer.
String value = .... <whatever read from the user>
int number = Integer.parseInt(value)
Then, if you like to get information on some of the digits, use modulus, ie:
number%10
will give you the most right integer (ie 127%10 is 7)
number%100
will give you 2 digits (ie 626%100 is 26)
Related
I am working on the problem to find the next greatest number with the same set of digits.
For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.
But when I take
int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. How can I overcome this ?
it is not possible in java to take the int values with leading zeros.
so for the value with leading zeros take it in string format.
but we can insert zeros
int n=7;
String str=String.format("%04d", n); //4 denotes the size of the string
System.out.println(str); // o/p->0007
It is not possible convert a 09 int value to a String of 9 since the value 09 can not be stored in an int.
int is not capable of storing trailing zeros.
Take this sample.
int foo = Integer.valueOf("09");
System.out.println(foo);
Output
9
So to solve your problem you should get a String from the user, validate it and parse it to an Integer[].
Solution
public Integer[] parseToInteger(String number) {
return Arrays.asList(number.toCharArray())
.stream()
.map(c -> Integer.valueOf(c.toString()))
.toArray(size -> new Integer[size]);
}
Now you have an Array of Integer.
Since leading 0's are dropped from integers there is no reason to support assigning such a value to an int.
If I want to convert 9 to '9' I usually just add '0' to it.
You can also do the following:
char c = Character.forDigit(9,10);
If you have a string of characters, you can do the following:
String str = "09";
List<Character> chrs =
str.chars().mapToObj(a -> Character.valueOf((char) a))
.collect(Collectors.toList());
System.out.println(chrs);
Prints
[0,9]
You are asking how to parse a number starting with a leading zero, but I get the feeling that you are actually on the worng track given the problem you are trying to resolve. So let's take one step backward, and lets make sure I understand your problem correctly.
You say that you have to find the "next greatest number with the same set of digits". So you are playing "Scrabble" with digits, trying to find the smalest number composed with the same digits that is strictly greater to the original number. For example, given the input "09", you would output "90", and for "123", you would output "132". Is that right? Let assume so.
Now, the real challenge here is how to determine the smalest number composed with thise digits that is stricly greater to the original number. Actually, there's a few possible strategies:
Enumerate all possible permutations of those digits, then filter out those that are not strictly greater to the original number, and then, among the remaining values, find the smallest value. That would be a very innefficient strategy, requiring both disproportionate memory and processing power. Please, don't consider this seriously (that is, unless you are actually coding for a Quantum Computer ;) ).
Set a variable to the initial number, then iteratively increment that variable by one until you eventually get a number that is composed of the same digits as the original values. That one might look simple to implement, but it actually hides some complexities (i.e. determining that two numbers are composed from the same digits is not trivial, special handling would be required to avoid endless loop if the initial number is actually the greatest value that can be formed with those digits). Anyway, this strategy would also be rather innefficient, requiring considerable processing power.
Iterate over the digits themselves, and determine exactly which digits have to be swapped/reordered to get the next number. This is actually very simple to implement (I just wrote it in less that 5 minutes), but require some thinking first. The algorithm is O(n log n), where n is the length of the number (in digits). Take a sheet of paper, write example numbers in columns, and try to understand the logic behind it. This is definitely the way to go.
All three strategies have one thing in common: they all require that you work (at some point at least) with digits rather than with the number itself. In the last strategy, you actually never need the actual value itself. You are simply playing Scrabble, with digits rather than letters.
So assuming you indeed want to implement strategy 3, here is what your main method might looks like (I wont expand more on this one, comments should be far enough):
public static void main(String[] args) {
// Read input number and parse it into an array of digit
String inputText = readLineFromUser();
int[] inputDigits = parseToDigits(inputText);
// Determine the next greater number
int[] outputDigits = findNextGreaterNumber(inputDigits);
// Output the resulting value
String outputText = joinDigits(outputDigits);
println(outputText);
}
So here's the point of all this discussion: the parseToDigits method takes a String and return an array of digits (I used int here to keep things simpler, but byte would actually have been enough). So basically, you want to take the characters of the input string, and convert that array to an array of integer, with each position in the output containing the value of the corresponding digit in the input. This can be written in various ways in Java, but I think the most simple would be with a simple for loop:
public static int[] parseToDigits(String input) {
char[] chars = input.toCharArray();
int[] digits = new int[chars.length];
for (int i = 0 ; i < chars.length ; i++)
digits[i] = Character.forDigit(chars[i], 10);
return digits;
}
Note that Character.forDigit(digit, radix) returns the value of character digit in base radix; if digit is not valid for the given base, forDigit returns 0. For simplicity, I'm skipping proper validation checking here. One could consider calling Character.isDigit(digit, radix) first to determine if a digit is acceptable, throwing an exception if it is not.
As to the opposite opperation, joinDigits, it would looks like:
public static String joinDigits(int[] digits) {
char[] chars = new char[digits.length];
for (int i = 0 ; i < digits.length ; i++)
chars[i] = Character.digit(digits[i], 10);
return new String(chars);
}
Hope that helps.
I'm learning JAVA and recently I had the same problem with a few training tasks.
I have a some numbers and some of them are starting with 0. I found out that these numbers are octal which means it won't be the number I wanted or it gives me an error (because of the "8" or the "9" because they are not octal digits) after I read it as an int or long...
Until now I only had to work with two digit numbers like 14 or 05.
I treated them as Strings and converted them into numbers with a function that checks all of the String numbers and convert them to numbers like this
String numStr = "02";
if(numStr.startsWith("0")) {
int num = getNumericValue(numStr.charAt(1));
} else {
int num = Integer.parseInt(numStr);
}
Now I have an unkown lot of number with an unknown number of digits (so maybe more than 2). I know that if I want I can use a loop and .substring(), but there must be an easier way.
Is there any way to simply ignore the zeros somehow?
Edit:
Until now I always edited the numbers I had to work with to be Strings because I couldn't find an easier way to solve the problem. When I had 0010 27 09 I had to declare it like:
String[] numbers = {"0010", "27", "09"};
Because if I declare it like this:
int[] numbers = {0010, 27, 09};
numbers[0] will be 8 instead of 10 and numbers[2] will give me an error
Actually I don't want to work with Strings. What I actually want is to read numbers starting with zero as numbers (eg.: int or long) but I want them to be decimal. The problem is that I have a lot of number from a source. I copied them into the code and edited it to be a declaration of an array. But I don't want to edit them to be Strings just to delete the zeros and make them numbers again.
I'm not quite sure what you want to achieve. Do you want to be able to read an Integer, given as String in a 8-based format (Case 1)? Or do you want to read such a String and interpret it as 10-based though it is 8-based (Case 2)?
Or do you simply want to know how to create such an Integer without manually converting it (Case 3)?
Case 1:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 8-based integer.
Integer number = Integer.parseInt(input, 8);
Case 2:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 10-based integer (default).
Integer number = Integer.parseInt(input);
Case 3:
// Java interprets this as octal number
int octal = 0235;
// Java interprets this as hexadecimal number
int hexa = 0x235
// Java interprets this as decimal number
int decimal = 235
You can expand Case 1 to a intelligent method by reacting to the indicator:
public Integer convert(final String input) {
String hexaIndicator = input.substring(0, 2);
if (hexaIndicator.equals("0x")) {
return Integer.parseInt(input.substring(2), 16);
} else {
String octaIndicator = input.substring(0, 1);
if (octaIndicator.equals("0")) {
return Integer.parseInt(input.substring(1), 8);
} else {
return Integer.parseInt(input);
}
}
}
I want to create a numerical representation of 5 letter codes. The codes may have 1-5 letters or digits.
The number must of course be unique. It is not absolutely necessairy that those numbers can be converted back to the ascii.
Thus I need digits from 0 to ZZZZZ
The resulting number size should be as small as possible.
I started with the following, but it's not quite what I want:
String a="ZZZZZZ";
for (int i = 0; i < a.length(); ++i) {
System.out.print(a.charAt(i)-'A'+1);
}
ZZZZZZ=262626262626
000000=-16-16-16-16-16-16
Start by enumerating all possible "digits" of your number:
Ten decimal digits 0 through 9
Twenty six letters A through Z
You have 36 possible "digits" for five positions, so the max number is 365=60,466,176. This number fits in an int.
You can make this number by calling Integer.parseInt, and passing a radix of 36:
System.out.println(Integer.parseInt("ABZXY", 36)); // 17355958
Demo.
Keep in mind that A134Z is already a number; it is only printed in Base-36 representation!
Albeit being just one sentence, the above should give you all you need to know to translate any 5-character string with 0-9 and A-Z into a number (and back).
Simplest solution - if letters are case insensitive is to use radix of 36 - full alphabet plus 10 digits. That way you get both functions for free - converting from string to long and from long to string like this:
long numericCode = Long.parseLong("zzzzz", 36); // gives 60466175
String stringCode = Long.toString(numericCode, 36); // gives "zzzzz"
You can treat the string as a number in base36 (where A=10, B=11 ... Z=35). This way, you will use exactly the numbers from 0 to 36^5-1, and each will be used exactly once.
I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.
Here is what I tried:
//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;
This returns to length of 3
The other thing I tried was:
int number = 0123;
int length = String.valueOf(number).length();
This also returned a length of 3.
Are there any alternatives to how I can obtain this length?
Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to #DavidConrad and #DrewKennedy for the octal precision.
Instead declare it as a String if you want to keep the leading 0
String number = "0123";
int length = number.length();
And then when you need the number, simply do Integer.parseInt(number)
Why is the syntax of octal notation in java 0xx ?
Java syntax was designed to be close to that of C, see eg page 20 at
How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008
by James Gosling (20_Gosling_keynote.pdf):
In turn, this is the way how octal constants are defined in C language:
If an integer constant begins with 0x or 0X, it is hexadecimal. If it
begins with the digit 0, it is octal. Otherwise, it is assumed to be
decimal...
Note that this part is a C&P of #gnat answer on programmers.stackexchange.
https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java
Use a string instead:
String number = "0123";
int length = number.length(); // equals 4
This doesn't work with an int, as the internal representation of 0123 is identical to 123. The program doesn't remember how the value was written, only the actual value.
What you can do is declare a string:
String number = "0123";
int numberLengthWithLeadingZeroes = number.length(); // == 4
int numberValue = Integer.parseInt(number); // == 123
If you really want to include leading 0's you could always store it in an array of of characters
example:
char[] abc = String.valueOf(number).toCharArray();
Then obviously you can figure out the length of the array.
As several people have pointed out already though, integers don't have leading 0's.
String abc=String.format("%04d", yournumber);
for zero-padding with length=4.
Refer to this link .
http://download.oracle.com/javase/7/docs/api/java/util/Formatter.html
this might help u ..
Integers in Java don't have leading zeroes. If you assign the value 0123 to your int or Integer variable, it will be interpreted as an octal constant rather than a decimal one, which can lead to subtle bugs.
Instead, if you want to keep leading zeroes, use a String, e.g.
String number = "0123";
This way you can also measure the length:
String number = "0123";
System.out.println(number.length());
For my current code, I'm creating a word calculator where words are inputted to represent numbers and the calculations are done within the code. The requirements is to input two numbers and an operator into the console. I was able to parse the input into three parts, the first number, the operator, and the second number.
My question is how should I approach when I convert the word into number form? For example, if a user inputted:
seven hundred eighty-eight plus ninety-five
How can I turn that into 788 and 95 so I can do the calculations within the code? My input needs to go up to 1000.
This is part of my code for dividing up the input.
import java.util.Scanner;
public class TextCalc2 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String in = input.nextLine();
in = in.toLowerCase();
while (!in.equals("quit")) {
if (in.contains("plus")){
String number1 = in.substring(0, in.indexOf("plus") - 1);
String number2 = in.substring(in.indexOf("plus") + 5, in.length());
String operator = in.substring(in.indexOf("plus"),in.indexOf("plus") + 5);
System.out.println(number1);
System.out.println(operator);
System.out.println(number2);
}
}
First of all there are problems in the way you are splitting the input (you have hard coded the operation). I would suggest splitting your input with " " (space) and then analyzing each part of the input separately.
You will have different types of words in your input, one is a single digit number, double digit number, operations and "hundred".
Then you should find which category first word of your input belongs to, if it has "-" it will be double digit, else look into other categories and search for it till you find it. Then based on category decide what you should do with it, if its a single digit, replace it with its equivalent. if its double digit, split and then replace each digit, if its operation store it and cut your input array from there so that you have separated the first value and second one, and if its hundred multiply previous single digit by 100.
After this parsing steps you will have something like this {"700","88"} , {"95"} and plus operation. now its easy to convert each string to its integer value using parse method and then apply the operation.
BTW, it would be easier to use Enum for your constants and just use their ordinal value. Also use the comment that Jared made for your double digit values.
Let me know if you still have question.