Convert number to reversed array of digits (Scanner + Print-Method) - java

I want to get an Array with the reversed number when I invoke the method (Given a random non-negative number, you have to return the digits of this number within an array in reverse order.)
I initalised a scanner, but whenever I execute, I only get the address in the heap I suppose (for example: [I#66a29884).
I know this problem also occurs when we have String, which why we have the toString-Method.
Is there a way I can print the array or the reversed numbers out in the console?
public class ConvertNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Long n = Long.parseLong(scanner.nextLine());
digitize(n);
}
public static int[] digitize(long n) {
int[] digitized = new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray() ;
System.out.println(digitized);
return digitized;
}
}

You have to change Long to String because [I#66a29884) is String. using java stream you can reverse string easily.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.*;
public class Main
{
public static String digitize(String n) {
return Stream.of(n)
.map(str->new StringBuilder(str).reverse())
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String n = scanner.next();
System.out.print(digitize(n));
}
}

Related

How do I combine two input variables into one line? [duplicate]

This question already has answers here:
How to read multiple inputs on same line in Java?
(5 answers)
Closed 12 months ago.
The given problem is to be able to input 2 digits in one line, instead of:
Input:
2
2
Output:
1
It should be:
Input:
2 2
Output:
1
To make more sense, here is my code:
import java.util.Scanner;
class Main
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
int sum = a % b;
System.out.print(sum);
input.close();
}
}
I want a code that only requires you to input two digits in one line instead of having to input the 2 digits separately.
you can use scanner inside another scanner like below and iterate it to get values
To sum you can you collectors.summingInt()
working sample:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class Summing {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine())
{
List<String> tokens = new ArrayList<>();
Scanner lineScanner = new Scanner(scanner.nextLine());
while (lineScanner.hasNext()) {
tokens.add(lineScanner.next());
}
lineScanner.close();
System.out.println(tokens.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.summingInt(Integer::intValue)));
}
scanner.close();
}
}
You can use one string input. Take this string and split it by whitespace then parse it by int.
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
var str = input.nextLine();
var delimeter = " ";
var subStr = str.split(delimeter);
var nums = new ArrayList<Integer>();
for(int i = 0; i < subStr.length; i++)
{
nums.add(Integer.parseInt(subStr[i]));
}
var sum = nums.get(0) % nums.get(1);
System.out.println(sum);
input.close();
}
}

How do store the data i have input and detected it's data type in Java?

I am making a program that detects the input data type t whether it's integer or double . I have don't the following code so far. But I don't know how to store the data I input.
Code:
import java.io.*;
import java.util.Scanner;
public class HeightCalc {
public static int temp,result;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
if (input.hasNextInt()) {
System.out.println("Integer.");
}
else if (input.hasNextFloat() || input.hasNextDouble()) {
System.out.println("Double.");
}
}
}
If you use the apache commons lib you can use StringUtils and NumberUtils.
In general define a variable for the scanner input and validate its content, validating the input directly is more restrictive.
import java.io.*;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math;
public class HeightCalc {
public static int temp,result;
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
String input = scanner.nextLine();
if (StringUtils.isNumeric(input))
{
System.out.println("Integer.");
}
else if (NumberUtils.isCreatable(input))
{
System.out.println("Double.");
}
System.out.println("Input:" + input);
}
}
You can store the input in a variable like in the above example.
String myInput = scanner.nextLine();
if I get it right you need to store input number value to one variable?
I would create Number inputValue variable and into it I would store values from scanner.
Number inputValue;
Scanner input = new Scanner (System.in);
if (input.hasNextInt())
{
inputValue = input.nextInt();
System.out.println("int.");
} else if (input.hasNextFloat() || input.hasNextDouble())
{
inputValue = input.nextDouble();
System.out.println("Double.");
}
inputValue will inherit class from .nextInt() or nextDouble().
However I would consider storing input to one variable to get rid of this condition and derivate other number classes from it.
Example for int
inputValue = input.nextDouble();
public int getIntValue(){
return inputValue.intValue();
}

working with variable number of arguments using scanner input class

While working with scanner input can we use var.. args with sc.nextInt()??
for example..(below code)
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[1]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
the output was ArrayIndexOutOfBoundsException:1 can any one explain about this...
values is just one variable, so args's length is 1, which means the only valid index is 0 (arrays are zero-based entities)
Your array size is 1 and trying to access 2nd value so use below code. I have change from args[1] to args[0].
ArrayIndexOutOfBoundsException arise when we try to access index value which is not present in array, not only for integers array but for all types of arrays.
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[0]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
use args[0] instead args[1] because your value store on

set of integers as input to print sum of their cubes

I am trying to solve this question. I tried many different ways, I get the correct output but the testcases are not passed(I dont know what are those testcases). I cant figure what is wrong.
Question:
Given a set of integers (separated by space), write a program to print the sum of their cubes.
Sample Input:
1 2 3 4 5
Sample Output:
225
Sample Input:
1 2
Sample Output:
9
Solution 2:
import java.io.*;
import java.util.*;
class Test{
public static void main(String []args)
{
int num,sum=0;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
num=sc2.nextInt();
sum=sum+num*num*num;
}
System.out.print(sum);
}
}
Your test cases most likely contain large integers as input. Use BigInteger to hold their cubes.
I modified my answer according to your needs. Now it gives sum of cubes of numbers in given input which are separated by spaces. Check this :-
import java.math.BigInteger;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.List;
import java.util.Scanner;
public class SumOfCubes {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String integers="";
Integer num=0;
BigInteger cube;
BigInteger sum=new BigInteger("0");
System.out.println("Enter Integers seperated by space");
integers=in.nextLine();
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s")) {
list.add(Integer.parseInt(s));
}
list.toArray();
for(int i=0;i<list.size();i++){
num=list.get(i);
cube=BigInteger.valueOf(num*num*num);
sum=sum.add(cube);
}
System.out.println("Sum of Cubes of numbers in given input = "+sum);
}
}
Hope it helps.
Update (by Andreas): Added boilerplate imports since #Ash seems unable to figure that out.
If you would like an implementation in more functional style (using Java 8+ streams), here is another suggestion:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] numbers = line.split("\\s+");
BigInteger sum = Arrays.asList(numbers)
.stream()
.map(BigInteger::new)
.map(bigInteger -> bigInteger.pow(3))
.reduce(BigInteger.ZERO, BigInteger::add);
System.out.println(sum);
}
}
Update: After #Andreas comments, the implementation can be even shorter:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
BigInteger sum = Pattern.compile("\\s+")
.splitAsStream(line)
.map(s -> new BigInteger(s).pow(3))
.reduce(BigInteger::add)
.orElse(BigInteger.ZERO);
System.out.println(sum);
}
}
I have changed your Solution 2 a little bit. Could you please confirm whether this passes the test or not.
import java.math.BigInteger;
import java.util.Scanner;
public class Test{
public static void main(String []args)
{
BigInteger sum=new BigInteger.ZERO;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
BigInteger num=new BigInteger(String.valueOf(sc2.nextInt()));
sum= sum.add(num.multiply(num).multiply(num));
}
System.out.print(sum);
}
}
import java.util.*;
class csum
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
long csum=0;
while(in.hasNextInt())
{
csum=csum+(long)Math.pow(in.nextInt(),3);
}
System.out.println(csum);
}
}
public static void main(String args[])
{
long num,count=0;
Scanner in=new Scanner(System.in);
while(in.hasNextInt())
{
num=in.nextInt();
count+=Math.pow(num,3);
}
System.out.println(count);
}
or
public Static vid main(String args[])
{
long count;
Scanner in=new Scanner(System.in);
String s=in.nextLine();
String[] t=s.split(" ");
for(i=0;i<t.length;i++)
{
count+=Math.pow(Integer.parseInt(t[i]),3);
}
System.out.println(count);
}
Used long instead of int. Thanks to Andreas and Matsev for the BigInteger idea.
import java.util.*;
class Test{
public static void main(String []args)
{
long num,sum=0;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
num=sc2.nextInt();
sum=sum+num*num*num;
}
System.out.println(sum);
}
}

how do i make a function that will accept a string and return the second character from the string?

For example if the function is given the string "ABCD" the function should return the letter B. This is code i've written so far but i'm getting a few errors which i've been trying to fix for three hours now!
import java.util.Scanner;
public class Stringg {
public static void main(String[] args)
{
System.out.print("Please enter a string: ");
mystring = Scanner.nextLine();
public static char getSecondChar(String myString) {
return myString.charAt(1);
}
System.out.println("The second character is " + getSecondChar (myString));
public class SecondChar {
public static char secondChar(String str){
char[] charArray=str.toCharArray();
if(charArray.length<=1)
{
System.out.println("String does not have 2nd character!");
return 0;
}
return charArray[1];
}
public static void main(String a[]){
String str="ABCD";
System.out.println(secondChar(str));
}
}
Try this. Do not create your function inside the main method. You will only need to call the function inside the main method to work.
public class Stringg {
public static char getSecondChar(String myString) {
return myString.charAt(1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a string: ");
String mystring = sc.nextLine();
System.out.println("The second character is " + getSecondChar(mystring));
}
}
In java, writing a function inside a function doesn't mean anything. You need to write functions in different scopes.

Categories