Converting multiple strings into one then parsing to int - java

I know this is not the simplest way to find a palindrome...but I was hoping someone might tell me if there is a way to convert multiple strings of integers into a single int. Maybe that builds a single string from others? Below I have an output that reverses the number you input. However, it comes out as a string of separate integers. Would I be able to typecast this into a single int then bool it against the original number somehow?
If I overlooked a topic similar to this, I'm sorry. I checked around and didn't find one that clearly solved my issue.
import java.util.Scanner;
public class Palindrone{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits:");
int num1 = input.nextInt();
int rev = 0;
//find last number
if(num1 >= 10){
rev = num1%10;
System.out.print(rev);
}
//find 2nd to last and 3rd from last
if(num1 >= 100){
rev = num1%100/10;
System.out.print(rev);
rev = num1%1000/100;
System.out.print(rev);
}
//find 4th from last
if(num1 >= 1000){
rev = num1%10000/1000;
System.out.print(rev);
}
//find 5th
if(num1 >= 10000){
rev = num1%100000/10000;
System.out.print(rev);
}
//find 6th
if(num1 >= 100000){
rev = num1%1000000/100000;
System.out.print(rev);
}
}
}
I'm trying to go from printing string (int rev)(int rev)(int rev)(int rev) to
one solid string then converting to int. Then if(newInt == num1) run statement.

You could go this way without the headache of string-int conversion:
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits: ");
String number = input.next();
System.out.println(new StringBuilder(number).reverse()); //prints reverse number

Easy, the following method uses Guava to perform the various steps:
public static boolean palindrome(int number) {
// Split into an array of digits and reverse
List<String> digits = Lists.transform(
Lists.reverse(
Lists.transform(
Lists.transform(
Lists.charactersOf(Integer.toString(number)),
Functions.toStringFunction()),
Ints.stringConverter())),
Ints.stringConverter().reverse());
// Join the strings and parse to an integer
int result = Integer.parseInt(Joiner.on("").join(digits));
// And check if a palindrome
return (result == number);
}
So, you could use the same technique with your code, if you create an empty list at the beginning, and add each parsed integer to the end of the list. However the way you are using the modulus operator with the fixed sequence of numbers multiplying by 10 each time is limiting. Instead, if you want to use this parsing method, consider a loop instead:
List<Integer> digits = Lists.newArrayList();
while (number > 10) {
int digit = number % 10;
digits.add(digit);
number /= 10;
}
Then reverse and transform back to a list of strings, and convert to an integer:
List<String> strings = Lists.transform(
Lists.reverse(digits),
Ints.stringConverter().reverse());
int result = Integer.parseInt(Joiner.on("").join(strings));
And again just check for equality with the original number.

Related

Problem in code and need a short code to solve problem

fist thing first , the code :
package com.company;
import java.util.Scanner;
public class index {
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
//let a= 2 7 4
int b= a%10;//4
int c=a/10;//27
int d= c%10;//7
int e=c/10;//2
//e=first num;
//d=middle num;
//b= last num ;
// for searching the greatest number
if (d>e && d>b )
System.out.printf(" the greatest number is %d%d%d",d,e,b);
else if(e>d && e>b )
System.out.printf(" the greatest number is %d%d%d",e,d,b);
else if (b>e && b>d )
System.out.printf(" the greatest number is %d%d%d",b,e,d);
// for the smallest number
else if(d<e && d<b && b>e)
System.out.printf(" the smallest number is %d%d%d",b,e,d);
else if(d<e && d<b && e>b)
System.out.printf(" the smallest number is %d%d%d",e,b,d);
else if (e<d && e<b && b>d)
System.out.printf(" the smallest number is %d%d%d",b,d,e);
else if(e<d && e<b && d>b)
System.out.printf(" the smallest number is %d%d%d",d,b,e);
else if (b<e && b<d && e>d)
System.out.printf(" the smallest number is %d%d%d",e,d,b);
else
System.out.printf(" the smallest number is %d%d%d",d,e,b);
}
}
now the problem:
this code is make to take number from the user as the input **of any three digit number ** and change it to the greatest number and smallest number ,
for example:
input number =274
output :
greatest number=742
smallest number=247
the above code is giving the greatest number but not the smallest number and the code is very lengthy ,
my output:
enter any three digit number
546
the greatest number is 654
so please help ,any error in code and if there is any short code then please help
I think that the problem is in the way of solution. As for me that is better to use some array or list and sort it. Something like that
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
array[i] = a % 10;
a = a / 10;
}
Arrays.sort(array);
int smallest = 0;
int greatest = 0;
for (int i = 0; i < 3; i++) {
smallest += array[i];
if (i != 2) {
smallest *= 10;
}
}
for (int i = 2; i > -1; i--) {
greatest += array[i];
if (i != 0) {
greatest *= 10;
}
}
System.out.println(Arrays.toString(array));
System.out.println(smallest);
System.out.println(greatest);
}
May I suggest a whole different approach?
void printGreatestAndSmallest(int number) {
char[] digits = String.valueOf(number).toCharArray();
Arrays.sort(digits);
String smallest = new String(digits);
String greatest = new StringBuilder(smallest).reverse().toString();
System.out.println("Greatest number is " + greatest);
System.out.println("Smallest number is " + smallest);
}
What happens here, is that we convert the digits to a char[], which can be sorted using Arrays.sort(...). This way, the smallest digit comes in front, the largest at the end. The char[] is converted back to a string with the String(char[]) constructor.
That is the smallest value. The largest value is the reverse of it! We can get the largest number using StringBuilder's reverse() method.
Note that this code cannot handle negative numbers.
The problem with your current approach is that it contains a lot of repetitions, and is not quite flexible; it is bound to an input of exactly three digits.
In order to fix the issue your are facing, remove the else keyword from the line else if(d<e && d<b && b>e). Each if-elseif-else statement only executes a single branch, but you need two branches to be executed, one for the smallest number, and one for the greatest number.
Further:
Use descriptive variable names. You have a comment in your code:
//e=first num;
//d=middle num;
//b= last num ;
but why don't you rename e, d and b to firstDigit, middleDigit and lastDigit respectively?
Follow the Java Naming Conventions. Variable and method names are written in camelCase, and class names in PascalCase. So class index should be class Index. Also make sure to rename index.java to Index.java.
You are defining variables with almost the same function: in your case firstNum, middleNum and lastNum. They all allow to store a specific digit of the input number. In such a case, you should use an array instead of separate variables. Loops work well with arrays.
If your code somehow iterates over all possible permutations of some collection, using if-else statements, that is probably not the best way.
For example:
if (d>e && d>b )
else if(e>d && e>b )
else if (b>e && b>d )
You should ask yourself: should these digits be in a certain order? The answer here is yes, they need to be sorted from low to high (and high to low). In that case, you probably want to sort them.

Take 6 digit input from user and store each digit in a single array in Java

I want to read in a 6 digit number e.g 123456 using the scanner and store each digit in an array of digits.
System.out.println("Please enter a 6 digit code");
int code = keyboard.nextInt();
And then somehow put that into:
int [] array = {1,2,3,4,5,6};
I need the array to be int type because I am going to find the product when I add together the odd numbers in the sequence (1+3+5) and add the even numbers (2+4+6) (as per specifications of the program) I then have some conditions that tell me which number to concatenate onto the end.
I can achieve this by pre-defining an array of numbers but I want this number to come from the user.
Unless there is another way of doing this without using arrays? I appreciate any pointers.
Here is my code when i have pre-defined the array and it's values.
int code[] = {1,2,3,4,5,6};
//add the numbers in odd positions together
int sum_odd_position = 0;
for (int i=0; i<6; i+=2)
{
sum_odd_position += code[i];
}
//convert the initial code into strings
String string_code = "";
String seven_digit_code = "";
//add numbers in even positions together
int sum_even_position=0;
for (int i=1; i<6; i+=2)
{
sum_even_position += code [i];
}
//add them both together
int sum_odd_plus_even = sum_odd_position + sum_even_position;
//calculate remainder by doing our answer mod 10
int remainder = sum_odd_plus_even % 10;
System.out.println("remainder = "+remainder);
//append digit onto result
if (remainder==0) {
//add a 0 onto the end
for (int i=0; i<6; i+=2)
{
string_code += code [i];
}
}
else {
//subtract remainder from 10 to derive the check digit
int check_digit = (10 - remainder);
//concatenate digits of array
for (int i=0; i<6; i++)
{
string_code += code[i];
}
//append check digit to string code
}
seven_digit_code = string_code + remainder;
System.out.println(seven_digit_code);
}
}
Start by reading in a string from the user. Create an array to put the digits into. Iterate through the string character by character. Convert each character to the appropriate int value and put it into the array.
String line = keyboard.nextLine();
int[] digits = new int[line.length()];
for (int i = 0; i < digits.length; ++i) {
char ch = line.charAt(i);
if (ch < '0' || ch > '9') {
throw new IllegalArgumentException("You were supposed to input decimal digits.");
}
digits[i] = ch - '0';
}
(Note also that there are various ways to parse a char as an int if ch-'0' does not suit your purposes.)
To send messages to the user:
System.out.println("Hello, please enter a 6 digit number: ");
To ask for input, make a scanner once and set the delimiter:
// do this once for the entire app
Scanner s = new Scanner(System.in);
s.useDelimiter("\r?\n");
Then to ask for stuff:
int nextInt = s.nextInt();
String nextString = s.next();
Pick whatever data type you want, and call the right nextX() method for this.
This sounds like you should be asking for a string and not a number (Because presumably 000000 is valid input, but that isn't really an integer), so you'd use next().
To check if it's 6 digits, there are many ways you can go. Presumably you need to turn that into an array anyway, so why not just loop through every character:
String in = s.next();
if (in.length() != 6) throw new IllegalArgumentException("6 digits required");
int[] digits = new int[6];
for (int i = 0; i < 6; i++) {
char c = in.charAt(i); // get character at position i
int digit = Character.digit(c, 10); // turn into digit
if (digit == -1) throw new IllegalArgumentException("digit required at pos " + i);
digits[i] = digit;
}
If you want to be less english/western-centric, or you want to add support for e.g. hexadecimal digits, there's some utility methods in Character you can use instead:
if (digit == -1) throw new IllegalArgumentException("digit required");
First, allocate a scanner and an array for the digits
Scanner input = new Scanner(System.in);
int[] digits = new int[6];
Prompt for the integer.
Use Math.log10 to check for proper number of digits
otherwise, re-prompt
then using division and remainder operators, fill array with digits. Filling is done in reverse to maintain order.
for (;;) {
System.out.print("Please enter six digit integer: ");
int val = input.nextInt();
// a little math. Get the exponent of the number
// and assign to an int. This will determine the number of digits.
if ((int) Math.log10(val) != 5) {
System.out
.println(val + " is not six digits in size.");
continue;
}
for (int i = 5; i >= 0; i--) {
digits[i] = val % 10;
val /= 10;
}
break;
}
System.out.println(Arrays.toString(digits));
For input of 123456 Prints
[1, 2, 3, 4, 5, 6]

How to sort strings by length

I have run into a problem of sorting strings from an Array. I was able to sort integers, but I don't really know how to sort the Strings from shortest to longest.
I have tried converting the Strings into integers by using Strings.length but I don't know how to convert them back into their original String.
String Handler;
System.out.println("\nNow we will sort String arrays.");
System.out.println("\nHow many words would you like to be sorted.");
Input = in.nextInt();
int Inputa = Input;
String[] Strings = new String [Input];
for (int a = 1; a <= Input; Input --) //will run however many times the user inputed it will
{
counter ++; //counter counts up
System.out.println("Number " + counter + ": "); //display
userinputString = in.next();
Strings[countera] = userinputString; //adds input to array
countera ++;
}
System.out.println("\nThe words you inputed are :");
System.out.println(Arrays.toString(Strings));
System.out.println("\nFrom shortest to longest the words are:");
counter = 0;
int[] String = new int [Strings.length];
for (int i = 0; i < Strings.length; i++) //will run however many times the user inputed it will
{
int a = Strings[i].length();
String[i] = a;
}
System.out.println(Arrays.toString(String));
I expected to be able to have the actual String to sort but the I'm getting numbers and am unable to find how to turn those numbers back into their string after sorting.
If you're allowed to use library functions, then you might want to do the following:
Arrays.sort(Strings, Comparator.comparing(String::length));
this works in Java 8 and above. Just make sure you import import java.util.*; at some point in your file.
It is not possible to convert them as you store only the length - there might be many different strings with same length.
Instead of this you can try to implement your own comparator and pass it to java's sort methods: given two strings returns 1 if first is longer, 0 if equal, -1 if shorter. You can also do this in a lambda comparator passed to the Arrays.sort().
(s1, s2) -> {
if (s1.length() < s2.length()) {
return -1;
}
return s1.length() > s2.length();
}

Comparing array element to zero?

Alright, so my goal is to complete the following assignment:
"Design and implement an application that determines and prints the number of odd, even, and zero digits in an integer value read from the keyboard.
SPECIFICATION OF PROMPTS, LABELS AND OUTPUT : Your code should not have any prompt at all. The input to this program is a single integer . After the integer is read, the output consists of three lines. The first line consists of the number of odd digits in the integer followed by the label "odd digits". The second line consists of the number of even digits in the integer followed by the label "even digits". The third line consists of the number of zero digits in the integer followed by the label "zero digits". For example, if 173048 were read in, the output would be:
3 odd digits
3 even digits
1 zero digits
SPECIFICATION OF NAMES: Your application class should be called DigitAnalyst"
And the code I have produced is:
import java.util.Scanner;
public class DigitAnalyst{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String num = scan.next();
int odd_count = 0;
int even_count = 0;
int zero_count = 0;
//input an int as a string, and set counter variables
int[] num_array = new int[num.length()];
//ready a array so we can so we can parse it sanely
for (int i =0; i < num.length(); i++)
{
num_array[i] = num.charAt(i);
}//fill the array with the values in the initial number using a loop
for ( int i=0;i< num_array.length; i++)
{
if (num_array[i] % 2 ==0)
{
if (num_array[i] ==0 )//the hell is going on here?
{
zero_count++;
}
else if (num_array[i] != 0)
{
even_count++;
}
}
else if (num_array[i] % 2 != 0)
{
odd_count++;
}
}//use this loop to check each part of the array
System.out.println(odd_count+ " odd digits");
System.out.println(even_count+" even digits");
System.out.println(zero_count+" zero digits");
}
}
And yet I keep getting the wrong output. More specifically, it returns the correct amount of odd numbers but it keeps counting 0 as an even and not as a zero.
I know where the problem is but I have no idea what is wrong, and I've spent a few hours on this.
If someone could point me in the right direction I'd be ectstatic.
When you encounter a problem that involves the manipulation of digits in an integer, the standard approach is to use an actual integer and the operator %, rather than strings. Instead of scan.next() use
int num = scan.nextInt();
And then you can do this:
do {
int digit = num % 10;
if ( digit == 0 ) {
zero_count ++;
} else if ( digit % 2 == 0 ) {
even_count ++;
} else {
odd_count ++;
}
num /= 10;
} while ( num > 0 );
The idea is that when you divide a number by 10, the remainder is exactly the rightmost digit, and the quotient will have all the other digits. That's simply how the decimal system works.
In this method you get the digit directly without calling any method, and you don't need any arrays.
If you assign the integer element with num.charAt(i) the ASCII value of the character is assigned and you get wrong results. In order to fix this, change
num_array[i] = num.charAt(i);
to
num_array[i] = Integer.parseInt(String.valueOf(num.charAt(i)));
or similar.
I'll give you some help here. First, charAt() returns the character at the index in the string, as a char data type. You're storing in an array of ints, which is assuming the numerical value of the character in the set, not the actual value.
Try this instead...
Change:
int[] num_array = new int[num.length()];
to:
char[] num_array = new char[num.length()];
and wrap all your num_array[i] references in your conditionals with:
Character.getNumericValue(num_array[i])
You should get your expected results.
Input = 12340
Output =
2 odd digits
2 even digits
1 zero digits

Java reading in a string and converting numbers in strings into Integers types

I am trying to take numbers from a users string (if it has numbers) and convert those numbers to their numerical value. I have the following code which takes in user input.
Ex: java Convert "55s" will just output the number 55, which i will store for later usage
{
char Element = 0;
double Sum = 0;
boolean Check = false;
for(String s: args) // taking in user input for command line
{
for (int i = 0; i<s.length(); i++)
{
Check = true;
Element = s.charAt(i); // converting the string into chars
Sum = convert_to_numb (Element, Check);
Check = false;
}
}
The input is a string in which i separate into chars and send it to my conversion functions. The idea i have follows
public static double convert_to_numb (char elem, boolean check) //trying to convert chars to numbers
{
char iter = elem;
double number = 0;
int count = 0;
while (check == true)
{
number = number + (iter - 48) * Math.pow(10,count);
System.out.println(iter);
count ++;
}
return number;
}
Here I am feeding in the chars to see if they're numbers and convert the actual numbers into their integer value. To try to clarify i would like to perform the following task given an example input of "55" covert it to 5*10^1 + 5*10^0 = 55. I would appreciate any help. Thanks.
Alright, I think I might know what you're trying to accomplish, though as others have mentioned it is a little unclear.
To address the code you just posted, I don't think it'll behave the way you expect. For starters, the Boolean variable 'Check' accomplishes nothing at the moment. convert_to_numb is only called while Check is true, so it's redundant.
Additionally, the sum isn't being stored anywhere as you loop through the string. Every time you obtain a sum, it overwrites the previous one.
Your convert_to_numb method is even more troubling; it contains an infinite loop. Since Check is always set to 'true', you essentially have a while(true) loop that will never end.
I'm going to assume that your objective here is to parse whichever Strings are input into the program looking for groups of consecutive digits. Then you want to store these groups of digits as integers, perhaps in an array if you find multiple.
Something like this might do the trick.
{
ArrayList<Integer> discovered = new ArrayList<Integer>();
for (String s : args) {
// contains previous consecutive digits (if any)
ArrayList<Integer> digits = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
// add digit to digit array
if (c.isDigit()) {
digits.add(c.getNumericValue())
}
// not a digit, so we clear the digit array
else {
// combine the array to form an integer
if (! digits.isEmpty()) {
int sum = 0;
int counter = 0;
for (Integer i : digits) {
sum += i * Math.pow(10, counter);
counter++;
}
discovered.add(sum);
digits.clear();
}
}
}
}
}
Note the use of ArrayLists and the Integer and Character wrapper classes. These all provide functionality that helps deal with edge-cases. For example, I'm not sure that (iter - 48) part would have worked in all cases.
Something like this:
public static void main(String[] args) {
String string = "55s";
String[] piece = string.split("[\\D]+");
for (int j = 0; j < piece.length; j++) {
if(piece[j].trim().length() > 0) {
System.out.println(piece[j]);
}
}
}
It will split your initial string, the rest you should do yourself.

Categories

Resources