Collections.reverse method not reversing entry - java

My code below is supposed to accept an integer from the user, and then print whatever integer they enter in reverse order. I am getting no errors, but when I run this program the integer is not being printed in reverse. Can someone please help me figure out why?
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String response;
System.out.println("Please enter a whole number.");
response = sc.next();
reverseDigit(response);
}
public static void reverseDigit(String digit) {
ArrayList al = new ArrayList();
al.add(digit);
Collections.reverse(al);
System.out.println("Your number in reverse order is: " + al);
}
}

You misinterpreted what Collections.reverse does. This method reverses the list that you gave, not its content. Since you called this method with a list having a single element, the result will be the same list.
If you want to reverse a String, please refer to this question.
As a side-note: do not use raw types like ArrayList, this will get into trouble. Prefer the type-safe way ArrayList<String>.

Try this code.
ArrayList al = new ArrayList();
al.add(new StringBuffer(digit).reverse().toString());

If you have a collection of one, it is the same in reverse order as forward.
If you want to reverse the string representation of an integer, you can use StringBuilder to reverse the digits.
StringBuilder sb = new StringBuilder();
sb.append(digits);
sb.reverse();
System.out.println("Your number in reverse order is: "+ sb);

If you want to reverse a String why are you adding it to a list ?
Use this :
String s = sc.next();
StringBuilder sb = new StringBuilder(s);
System.out.println(sb.reverse());

The reverse(List<?>) method is used to reverse the order of the elements in the specified list. Since there is only one item in your collection, reverse order is same as the initial list. You can use the below code as you are trying to reverse an integer.
package com.stackoverflow.answer;
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a whole number: ");
int number = scanner.nextInt();
System.out.println(String.format("Your number in reverse order is: %d", reverse(number)));
scanner.close();
}
public static int reverse(int x) {
return reverse(x, 0);
}
private static int reverse(int x, int y) {
return x == 0 ? y : reverse(x / 10, y * 10 + x % 10);
}
}

Related

How do I fix the "float cannot be converted into float[]" error in the below code?

I have written a small program to take number of elements from user and the price of those elements and then print the price.
But the 12th line of this code giving error "float cannot be converted into float[]", and I am not able to figure out how to resolve this. Please provide some help or any modification in the code if needed.
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order: ");
float[] price =new float[N];
for(int i=0; i<N;i++){
price=s1.nextFloat();
System.out.println(price);
}
}
}
In your code, price is an array
float[] price = ...
And an array of type T consists of elements, each of type T. So you need to assign an element of the array to a float e.g.
price[i] = myFloat;
Formatting and nomenclature are a must when you write code as it makes your code more readable and easy to understand. I have formatted your code and also updated for proper inputs.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
System.out.println("enter the number of elements :");
Scanner s1 = null;
try {
s1 = new Scanner(System.in);
int totalElements = s1.nextInt();
System.out.println("enter the price of all the elements in ascending order :");
float[] price = new float[totalElements];
for (int i = 0; i < totalElements; i++) {
price[i] = s1.nextFloat();
System.out.println(Arrays.toString(price));
}
} finally {
if (s1 != null) {
s1.close();
}
}
}
}
Please take care of below things:
Variable names should start with small case and follow camel casing.
Scanner whenever used needs to be closed.
Your error is resolved by assigning float to one position in array and not to the array. E.g. price[i] = s1.nextFloat();
To print an array, use the Arrays.toString() function.
Happy Coding
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order :");
float[] price =new float[N];
for(int i=0; i<N;i++){
price[i]=s1.nextFloat();
System.out.println(price[i]);
}
}
}
It should be like this because in the printing statement you've called the whole array that won't give you the element but the some numbers and alphabets thing and also the statement where you're reading the prices by scanner you are not telling the computer to put your price at which index of the array that's why it's giving this error.

Calculating the sum of number and its reverse in java

My question is based on a number manipulation in java. please, give any example for calculating the sum of any numbers and its reverse in java.for example, 123+321.
Public int sumReverse(int num){
int orignal=num;
int reverse=0;
While(orignal>0){
int remainder=orignal%10;
reverse=reverse*10+remainder;
orignal=orignal/10;
}
return num+reverse;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String n2s="";
int n1= sc.nextInt();
String n1s= String.valueOf(n1); //let n1s be the String of n1
for (int i=1;i<=n1s.length();i++){
n2s+=n1s.charAt(n1s.length()-i);
}
System.out.println(n2s);
int n2=Integer.valueOf(n2s);
int adit=n1+n2;
System.out.println(n1s+" + "+n2s +" = "+ adit);
}
In order to manipulate numbers they way you're looking for, it is easier to work that answer with the String of that number.
Scanner allow the user to type any number he/she wants to manipulate.
Hope this is usefull for you.
You could use StringBuilder also
int num = 123;
StringBuilder ob = new StringBuilder(Integer.toString(num));
ob.reverse();
System.out.println(num + Integer.valueOf(ob.toString()));
Store the data in StringBuilder and then add it to the original after reversing it.

Knapsack Solution using Recursion and Array

I would like to know the best possible way to modify this code. Instead of adding the integers to an array in the code itself, I would like the user to input the different weights and the capacity via keyboard.
Now I am currently having compiling errors when inserting the data. I believe the problem lies within the for loop.
import java.util.*;
public class NN01276494 {
public static ArrayList <Double> sack = new ArrayList <Double> ();
public static void main(String [] args){
Scanner in = new Scanner (System.in);
int i =0;
for(i = 0; i<sack.length; i++){
System.out.println("Enter Capacity");
sack.size(in.nextDouble());
}
while (in.hasNextDouble()){
System.out.print("Enter weights");
sack.add(in.nextDouble());
i++;
}
}
public static Boolean knapsackproblem(double targetWeight, int index)
{
Boolean complete = false;
if(index == sack.size()) return false;
if(sack.get(index) == targetWeight)
{
System.out.print("Answer: " + sack.get(index) + " ");
complete = true;
}; //DONE
if(sack.get(index) < targetWeight)
{
complete = knapsackproblem(targetWeight-sack.get(index), index+1);
if(complete) System.out.print(sack.get(index) + " ");
for(int i = index+1; i < sack.size(); i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i);
}
}
if(sack.get(index) > targetWeight) complete =
knapsackproblem(targetWeight, index+1);
return complete;
}
}
The most common way to accept user input in java is the Scanner class. This allows your users to input into the console, and your program to use their input. Here is the javadoc that details scanners in detail, but here's all you need to do to accept integer inputs from your users:
First, import the scanner dictionary so you can use it.
import java.util.Scanner;
This will give you access to the Scanner library. To construct the scanner, you need to specify an input stream in the declaration. To make the console this input stream, declare it like so:
Scanner nameOfScanner = new Scanner(System.in);
Now, to get the integers for the array, use the method .nextInt() as many times as you want. Make sure to ask the user separately for each input, and if you want the user to be able to control the size of the array, you can also ask the user for that. Just in case you don't know, you can declare an array to have a certain size, but not specify what is going to be in each location until later like so:
int[] nameOfArray = new int[sizeOfArray];
On a separate note, I noticed that you had a semicolon after the closing bracket of your if statement in the middle of the knapsackproblem() method. I don't know if that's a typo in your question or actually in your code, but it really shouldn't be there.
I hope this helps, and good luck coding!
I've modified your code so user can input the array via an ArrayList :-using ArrayList user can input data without regard to length just enter as many values as you want then at the end type any letter for ex:[Out] then your method should start working :).
import java.util.*;
public class knapsack {
public static void main(String [] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter Capacity");
int y = in.nextInt();
double [] sack = new double [y];
System.out.println("enter values");
for (int i =0;i<y;i++){
sack[i]=in.nextDouble();
}
}
public static Boolean knapsackproblem(double targetWeight, int index ,
double [] sack)
{
Boolean complete = false;
if(index == sack.length) return false;
if(sack[index] == targetWeight)
{
System.out.print("Answer: " + sack[index] + " ");
complete = true;
}; //DONE
if(sack[index] < targetWeight)
{
complete = knapsackproblem(targetWeight-sack[index], index+1,sack);
//keep going
if(complete) System.out.print(sack[index] + " ");
for(int i = index+1; i < sack.length; i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i,sack);
}
}
if(sack[index] > targetWeight) complete = knapsackproblem(targetWeight,
index+1,sack);
return complete;
}
}
Hope it helps.Also I've fixed your recursion since you wrote knapsack( instead of knapsackproblem(.ArrayList comes from java,util package which also includes the Scanner class I just got them all using * ArrayList is a class that has its own methods like .size() and .add().

Create java list from user input

I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method

Unable to obtain the correct product of numbers when used with Math.pow()

I was trying to write a recursive function which gets a string and returns the integer form of it. I know that this can be done easily in Java using Integer.parseInt. This is a part of an exercise I am doing.
For the following code, when I enter "963" as the input, it returns the output as "6291". So, i checked if the array was getting passed properly and it was.
To check the multiplication, I split and printed the product each time, which gave 5700, 540 and 51, which correctly sum up to 6291. (which actually should have been 900 + 60 + 3 = 963). I'm unable to figure out what is wrong in my program.
import java.io.*;
import java.lang.*;
class RecConvert
{
static double i=0;
static double sum=0;
public static void main(String[] args) throws IOException
{
BufferedReader B = new BufferedReader(new InputStreamReader(System.in));
String input = B.readLine();
int number = RecursiveConvert(input);
System.out.println("The number is "+number);
}
static int RecursiveConvert(String input)
{
char[] charArray = input.toCharArray();
if(i < charArray.length)
{
sum = sum + (charArray[(int)i]) * ( (double)Math.pow(10.0,charArray.length-i-1) );
i++;
return RecursiveConvert(input);
}
else
return (int)sum;
}
}
This is your problem (charArray[(int)i]). You're multiplying a char with a double. Character.getNumericValue(charArray[(int)i]) will solve it.

Categories

Resources