Code in Java to add two numbers is printing out sum backwards? - java

The following Java program (prints out addition problem of two given numbers) is printing the answer backwards ( for example, 563 instead of 365). How would I modify it so that it prints out the correct answer?
Note: I know that Im completing this problem in an unnecessarily complicated manner, but this is because we are only allowed to use primitive data types.
Thankyou.
//getting the number from user
Scanner linput = new Scanner(System.in);
System.out.print("Enter the first number:");
num = linput.nextInt();
System.out.println ("Enter the second number:");
num2 = linput.nextInt();
System.out.println (num);
System.out.println ("+");
System.out.println(num2);
System.out.println ("=======");
//making a copy of the input number
temp = num;
temp2 = num2;
//counting digits in the input number
while(num > 0)
{
num = num / 10;
count++;
}
while(num2 > 0)
{
num2 = num2 / 10;
count2++;
}
int answer = 0;
while(temp > 0 && temp2>0)
{
digit = temp % 10;
temp = temp / 10;
count--;
digit2 = temp2 % 10;
temp2 = temp2 / 10;
count2--;
answer = digit+digit2;
System.out.print(answer);
}

You problem statement is very unclear. If it's just simple addition of two numbers then you've really overcomplicated your implementation.
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number:");
int num = input.nextInt();
System.out.print("Enter the second number:");
int num2 = input.nextInt();
System.out.print(num + " + " + num2 + " = " + (num + num2));

I totally agree with all comments that this is over complicated to do a sum. But the answer to the initial question why the result is printed backwards is that that you calculate the sum from right to left (units, tens, hundreds, ...) but print them left to right (default behavior of print)

Related

Why does my for loop return only half the elements I expect it to?

I would like to receive user input on n elements for the Fibonacci sequence. The scanner and calculations themselves seem to be working fine -- the input is successfully grabbed and the sequence calculated. It's even able to correctly disqualify inputs of a negative value. However, it is not actually returning 'n' elements. Curiously, I noticed that the loop consistently returns exactly half the elements requested, albeit in the correct order. If n = 20, the first 10 numbers are returned.
Here's the code:
public class fibonacci_input {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);
int num1 = 0;
int num2 = 1;
int n;
System.out.println("How many elements would you like in your Fibonacci sequence?");
n = myObj.nextInt();
if (n < 0)
System.out.println("Positive numbers only!");
else
System.out.println("Your Fibonacci sequence with " + n + " elements is:");
{ for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
++i;
}
}
}
}
I'm struggling to imagine what the problem could be. I first thought it might be a problem with the test condition statement, but similar (working) solutions online seem to have their loops formatted almost identically. Is it perhaps a problem with my variable declarations? I've tried multiple changes to no avail so would appreciate another set of eyes :)
You could just delete the second i++; statement in your code, this one is making the for loop run half times as expected, since the i variable is being incremented twice on each iteration
public class fibonacci_input {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int num1 = 0;
int num2 = 1;
int n;
System.out.println("How many elements would you like in your Fibonacci sequence?");
n = myObj.nextInt();
if (n < 0)
System.out.println("Positive numbers only!");
else
System.out.println("Your Fibonacci sequence with " + n + " elements is:");
{ for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
//++i;
}
}
}
}

How can I print numbers between two numbers that I enter?

I am creating a program which asks the user to enter two numbers. It will then print the numbers the user entered and the numbers between the two numbers in numerical order. I declared and initialized two variables, which are 'number1' and 'number2'.
int number1;
int number2;
do{
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number: " );
number1 = input.nextInt();
System.out.print("Enter the second number: " );
number2 = input.nextInt();
if(number1 == number2)
{
System.out.println("The numbers you entered equal with each other. Try again.\n");
}
}while(number1 == number2);
if (number1 > number2)
{
for(int a = number2; a <= number1; a++)
{
System.out.print(a + " ");
}
}
else
{
for(int a = number1; a <= number2; a++)
{
System.out.print(a + " ");
}
}
How do I make it so it also prints only the numbers between 'number1' and 'number2'?
The first part of your code was fine, if you want to do it this way.
Scanner scanner = new Scanner(System.in);
int first, second;
do {
System.out.print("Enter the first number: ");
first = scanner.nextInt();
System.out.print("Enter the second number: ");
second = scanner.nextInt();
if (first == second) {
System.out.println("The numbers you entered equal with each other. Try again.\n");
}
} while (first == second);
For the second part, I'd recommend determining which number is which (smaller/bigger) instead of using duplicate code. Also you need to only cycle through numbers in between the numbers you chose, so you have to change your for cycle
//determine which number is bigger/smaller
int smaller = Math.min(first, second);
int bigger = Math.max(first, second);
for(int i = smaller+1 ; i < bigger ; i++){
System.out.print(i + " ");
}
The only odd scenario here is where you input two numbers which are adjacent, which will output no numbers. For example 3 and 4.
int max = Math.max(number1, number2);
for(int i = (max == number1 ? number2 : number1) + 1 ; i < max ; i++) {
System.out.println(i);
}

Create a java application that displays the sum of the digits of a number

I am relatively new to Java and I'm currently learning while, do while and for loops. I want to create an application that displays the sum of the digits of a number using these concepts but I have no idea how. I previously created an application that displayed ONLY THE DIGITS of a number. Here it is.
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
}
I'm trying to think of a possible way to expand on this program, but I have no idea why. Once again, this program is not what I need, what I need is somehow to sum the digits of a number using for or while loops. Thank you!
not much code has to be added for summing the digits :
First solution : using a substract with '0' character
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + (sdigit.charAt(i) - '0');
}
System.out.println("Sum is : "+sum);
Second solution : using Integer.parseInt which converts String to int :
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + Integer.parseInt(sdigit.subString(i,i+1));
}
System.out.println("Sum is : "+sum);
int digit;
System.out.println("Enter a positive integer: ");
number= Integer.parseInt(System.console().readLine());
int sum=0;
int currDigit = 0;
while( number / 10 > 0) {
currDigit = number % 10; //fetching last digit
System.out.println(currDigit);
sum = sum + currDigit;
number = number / 10;
}

While Loop - Sum of even numbers between two inclusive integers

EDIT: Lol I would've never thought you guys would be such savages. I thought this would be the right place for a college student to come and seek for answers. If I didn't care, why would I even be here.. Basically my question is different from the other ones because I do need the first loop to state my even numbers ie: 10 12 14 16 18 20. I sincerely hoped I would get some feedback on how to reinstate the original value of firstNum for the second loop, not criticism expecting to get selected as an answer for points in a matter of seconds.
I've implemented a code that I saw as an answer in a very similar question on the forum. Yet when I compile it, the output for my sum code doesn't return anything. It's just blank. Can I get some feedback on what I am missing or doing wrong? Thank you. BTW I can only use while loop.
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
int sum = 0;
if (mod != 0)
{
firstNum++;
}
System.out.print("Even numbers: ");
while (firstNum <= secondNum)
{
System.out.print(firstNum + " ");
firstNum += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
while (firstNum <= secondNum)
{
System.out.print(sum);
sum += firstNum;
firstNum += 2;
}
The first loop only prints the even numbers, it can not add because the firstNum reaches the secondNum.
If you want to keep the same code you have, you only need to add a new variable that prints even numbers. So the first loop will print the even numbers and the second loop will do the sum.
For example:
int evenNumber;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
int sum = 0;
if (mod != 0) {
firstNum++;
}
evenNumber = firstNum;
System.out.print("Even numbers: ");
while (evenNumber <= secondNum) {
System.out.print(evenNumber + " ");
evenNumber += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
while (firstNum <= secondNum) {
sum += firstNum;
firstNum += 2;
}
System.out.println(sum);
This code is not optimal, but it complies with what you need. But if you want to do better, you can do it like this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
int total = 0;
System.out.print("Even Numbers: ");
while (firstNum <= secondNum) {
if (firstNum % 2 == 0) {
System.out.print(firstNum + " ");
total += firstNum;
}
firstNum++;
}
System.out.println("\nSum: " + total);
During your first while, you already changed the value of firstNum. So basically, when you arrive to the second while, you don't even enter it.
I would simply change the first loop and delete the second one :
while (firstNum <= secondNum) {
System.out.print(firstNum + " ");
sum += firstNum;
firstNum += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
System.out.println(sum);
In your first while loop -
while (firstNum <= secondNum){
System.out.print(firstNum + " ");
firstNum += 2;
}
you keep incrementing variable firstNum until you reach secondNum, so the condition of the second while loop (firstNum <= secondNum) will never evaluates to true.
A very simple way to achieve your goal can be as follows.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
int total = 0;
while(firstNum <= secondNum){
if(firstNum%2 == 0)
total += firstNum;
firstNum++;
}
System.out.println("Sum: " + total);

Fibonnaci sequence explanation

Can someone explain to me some parts of this code:
public static void sequence(int nterms){
int num1 = 0;
int num2 = 1;
int num = 2;
if (nterms <= 0){
System.out.println("Enter a positive integer");
}
else if (nterms == 1){
System.out.println(" fibonacci sequence: " + num1);
}
else{
System.out.println(num1 );
System.out.println(num2);
while (num < nterms){
int nth = num1 + num2;
System.out.println(nth);
num1 = num2;
num2 = nth;
num++;
}
}
}
The number sequence that's in the output is correct. So the code works. But why do you do num++ in the end? I know nth is previous two numbers added together but why do you nterms == 1 and print "" +num1? I don't get that.
Here it is
public static void sequence(int nterms){
/*instancation of needed variables : nth = num1+numb2 later in the code*/
int num1 = 0;
int num2 = 1;
/*num is the number of term you've encoutered, as the first two are in
the initialization, you start at 2*/
int num = 2;
if (nterms <= 0){ //check wether the function has a correct input or not*/
System.out.println("Enter a positive integer");
}
else if (nterms == 1){ /*if it's the first term we know in num1*/
System.out.println(" fibonacci sequence: " + num1);
}
else{
System.out.println(num1);/*we print the first two terms*/
System.out.println(num2);
while (num < nterms){ /*we loop till we reached the wanted number*/
/*we know a term is equal to the two terms before it, at least I hope you do*/
int nth = num1 + num2;
System.out.println(nth); /*we've got our number so we print it*/
num1 = num2; /*we make sure num1 and num2 are the last two encountered, so num1 becomre num2 and num2 become the current term (nth)*/
num2 = nth;
num++;/*we increment the variable as we've met printed a new term*/
}
}
}

Categories