Reverse integer including 0's in java - java

I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you

Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).

You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}

Related

Average calculator with user input Java - " java.util.NoSuchElementException: No line found "

I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}

Averaging User Input, looping input until negative number is entered

import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.

Java StringIndexOutOfBounds When Using Substring

I get a StringIndexOutOfBounds error with this Java program on the line:
String num3 = lottoString.substring(2,2);
Telling me that 2 is out of the range, but this code should randomly pick a three digit lottery number ranging from 000 through 999. What is my error?
import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
//Declare and initialize variables and objects
Scanner input = new Scanner(System.in);
String lottoString = "";
//Generate a 3-digit "lottery" number composed of random numbers
//Simulate a lottery by drawing one number at a time and
//concatenating it to the string
//Identify the repeated steps and use a for loop structure
for(int randomGen=0; randomGen < 3; randomGen++){
int lotNums = (int)(Math.random()*10);
lottoString = Integer.toString(lotNums);
}
String num1 = lottoString.substring(0,0);
String num2 = lottoString.substring(1,1);
String num3 = lottoString.substring(2,2);
String num12 = num1 + num2;
String num23 = num2 + num3;
String num123 = num1 + num2 + num3;
//Input: Ask user to guess 3 digit number
System.out.println("Please enter your three numbers (e.g. 123): ");
String userGuess = input.next();
//Compare the user's guess to the lottery number and report results
if(userGuess.equals(num123)){
System.out.println("Winner: " + num123);
System.out.println("Congratulations, both pairs matched!");
}else if(userGuess.substring(0,2).equals(num12)){
System.out.println("Winner: " + num123);
System.out.println("Congratulations, the front pair matched!");
}else if(userGuess.substring(1,3).equals(num23)){
System.out.println("Winner: " + num123);
System.out.println("Congratulations, the end pair matched!");
}else{
System.out.println("Winner: " + num123);
System.out.println("Sorry, no matches! You only had one chance out of 100 to win anyway.");
}
}
}
As mentioned in the other answer, every time you iterate over your loop, you reset the value of lottoString to just be one digit. You need to append to it, like this:
lottoString += Integer.toString(lotNums);
Your other problem is your use of the substring method. If both index positions are the same, such as 0,0, it returns an empty String. What you want is this:
String num1 = lottoString.substring(0,1);
String num2 = lottoString.substring(1,2);
String num3 = lottoString.substring(2,3);
for(int randomGen=0; randomGen < 3; randomGen++){
int lotNums = (int)(Math.random()*10);
lottoString = Integer.toString(lotNums);
}
You're assignining the result of Integer.toString() to lottoString. lotNums is a number between 0 and 9.
I guess you want
lottoString += Integer.toString(lotNums);

How can I make my user aware of how many numbers they input whether it was negative or positive

So far I have this program which is already pretty close to what I want anyways. But am trying to figure out a way after the user input all his/her number he can know if he input 3 negative numbers and 4 posistive numbers
so let say he inputs -7,-8,-3,2,3,4,2 it says you have input 3 negative numbers and 4 postive numbers
import java.util.*;
public class Testing2 {
public static void main(String[] args) {
int numbers;
System.out.println("Input seven numbers");
for (int i = 1; i <8; i++){
Scanner Nums = new Scanner(System.in);
numbers = Nums.nextInt ();
if (numbers < 0){
System.out.println("You have " + numbers + " numbers that are negative");
} else {
System.out.println("You have "+ numbers + " numbers that are postive");
}
}
}
}
and what does it mean Resource leak: nums is never closed
I am using eclipse and this what shows up. Anyone know why?S
Try this:
import java.util.*;
public class Testing2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Don't need to close as System.in
int numNegative = 0, numPositive = 0;
System.out.println("Input seven numbers");
for (int i = 1; i < 8; i++){
int number = scanner.nextInt();
if (number >= 0){ // Is the number positive or 0
numPositive++;
} else { // Otherwise
numNegative++;
}
}
System.out.println("You have " + numPositive + " numbers that are positive");
System.out.println("You have " + numNegative + " numbers that are negative");
}
}
One way to do it is to use an array to keep track of your seven numbers, and two variables for keeping track of the positive or negative numbers(e.g. pos_numbers and neg_numbers),
This way, each time you receive input from the user, the if else statement tests whether the number is positive or negative, and if its positive then it will increment the pos_numbers variable by one, and if its negative then it will increment the neg_numbers variable by one. After the user is finished entering the numbers, the program will display the values of pos_numbers and neg_numbers to show how many positive numbers and negative numbers were input by the user respectively.
Also, it's a good idea to put the line where you create the Scanner object before the for loop, since this only needs to be done once instead of multiple times.
Here is the code:
import java.util.*;
class Testing2 {
public static void main(String[] args) {
int[] numbers = new int[7];
int pos_numbers = 0;
int neg_numbers = 0;
Scanner Nums = new Scanner(System.in);
System.out.println("Input seven numbers");
for (int i = 0; i <7; i++) {
numbers[i] = Nums.nextInt();
if (numbers[i] < 0) neg_numbers++;
else pos_numbers++;
}
System.out.println("You have " + neg_numbers + " numbers that are negative");
System.out.println("You have "+ pos_numbers + " numbers that are postive");
}
}

Inputting a number then reversing it

Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}

Categories