Scanner sal = new Scanner(System.in);
System.out.print("Enter first_salary: ");
int Salary1 = sal.nextInt();
System.out.print("Enter second_salary : ");
int Salary2 = sal.nextInt();
System.out.print("Combined Salary is " + Salary1 + Salary2);
I am trying to get user input twice, and then print the sum. Instead, the output is concatenating the numbers instead of actually adding them.
Because the + operator associates left to right. Your argument is equivalent to the explicit
(("Combined Salary is " + Salary1) + Salary2)
Since ("Combined Salary is " + Salary1) results in a string, you will concatenate strings. To group differently, adjust the order of operations with parentheses:
System.out.print("Combined Salary is " + (Salary1 + Salary2));
As to why this happens, #MadPhysicist's answer covers that.
As to how to avoid this you can either use parentheses as they said or you can use string formatting, like this:
System.out.println("Combined Salary is %d".formatted(Salary1 + Salary2));
String has had the formatted method since Java 15. If you're stuck with an older version you can use the static format method instead:
System.out.println(String.format("Combined Salary is %d", Salary1 + Salary2));
Related
i converted my java code into a python code and how to decrement the variable inside of the for loop in the python? I try to decrease the index by 1 if it is inside the if statement, but apparently I can't do that. Is there any other way that I can decrease i in a for loop?
Java Code:
for(int i = 1; i <= 3; i++)
{
System.out.print("Enter Movie " + i + " of " + 3 + " : ");
String inputMovie = sc.nextLine();
if (inputMovie.equals(""))
{
System.out.println("Please input a movie name.");
System.out.println("");
i--;
}
else
movies.offer("'"+inputMovie+"'");
}
Python Code:
for i in range(1,4):
inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
i-=1
pass
else:
movies.append(inputMovie)
pass
Output: well if we look at the output it is still incrementing not decrementing the i
Enter Movie 1 of 3 :
Please input a movie name
Enter Movie 2 of 3 :
Please input a movie name
Enter Movie 3 of 3 :
Please input a movie name
Python doesn't let you alter the iterator in a for loop. As soon as the next iteration of the loop comes by, the iterator will be the next value of the iterable.
This is also because range doesn't behave like an actual Java-like for loop. Instead, it keeps generating numbers within the range (you can see this by typing list(range(10)) in a Python interpreter, it will make a list of numbers from 0 to 9.
If you want to modify the iterator, you should go old-school with a while loop instead:
i = 1
while i <= 3:
inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
i-=1
else:
movies.append(inputMovie)
i = i + 1
This should do the same as your Java code, as I'm just moving the three instructions from the Java for loop to their places. Notice pass is not required as it is a statement with no effect.
For the sake of optimization, let me say you don't really need to decrement the iterator, just avoid incrementing it instead. I keep this solution separate from the original answer since it is a significant deviation from your original design:
i = 1
while i <= 3:
inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
else:
movies.append(inputMovie)
i = i + 1
All I've done is remove the decrement and push the increment to the else block so it is only run if a movie name has been input.
The for loop in Python is more like for-each. So the loop value(i) will get updated to the next value regardless of the changes/updates in the loop.
A better way to do this would be to use a while loop.
i = 1
while i <= 3:
inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
i-=1
pass
else:
movies.append(inputMovie)
i+=1
pass
you should use a while statement
"Unfortunately" the for loop will keep "memory" and reassign to the next value at each iteration
i = 1
while i < 4:
inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie == "":
print("Please input a movie name")
print("")
i-=1
else:
movies.append(inputMovie)
i+=1
the pass instruction is irrelevant, you can omit that
pass statement
range(low,high) generates a sequence consisting of elements starting from low and ending at high-1. That's why your i-=1 doesn't work, since I is iterating in that list.
The easiest alternative here would be to use a while loop.
while i<target:
if something:
#do something
i += 1
You have to set your range() function correctly. In order to decrement the loop you can use while loop or you can change your algorithm and set the for loop but now what you can do is if you can select the range functions step value to -1. Please try it to check the code coz i also have the same question in mind like you.
I'm taking my java class, and I'm working on a Tsubo calculator for my assignment. I don't usually ask questions on stack overflow so forgive me if this seems basic. I've done some searching here and tried some of the solutions but none have worked in my case. I'm going to copy just part of my conversion below
```
System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftResultAsString + " Tsubo"); `
When I do this, it tells me I can't format a double that the type is not applicable to arguments for DecimalFormat.
When I change it to look like this (offending line is commented out)
' System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftFormatted + " Tsubo");
The program compiles and runs, and when I use 5238 as an input number, then my output looks like this --> 5238.0 is equal to :java.text.DecimalFormat#674dc Tsubo
instead of actually displaying the answer which is 325.07.
I've also tried using some regex formatting using the stringFormat but i wind up getting illegalformatting exception.
Long story short, What I'm trying to achieve is an output that is formatted to 2 decimal places, and then converted to a string that the system outputs as an answer. What am I missing? Is this Decimal Format automatically converting this to a string object?
DecimalFormat is used to produce a formatted String. If you print it directly, it will show its (kind of, it's called idenity hashcode) memory address cause that is what the DecimalFormat.toString() does.
Instead, you should use it to produce your output string and print that directly.
As follows:
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
String out = sqftFormatted.format(sqftResult); // or whatever you want to print
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + out + " Tsubo");
See docs for more details
I am using a driver class to create an object of another class. When I enter the pet weight or integer the number comes out to 0.0. All of the weight variables are declared as double so I do not know why it is doing this.
import java.util.Scanner;
public class PetAssignment {
public static void main(String[] args)
{
String nameAndType;
int yrs;
double lbs;
//Scanner object for the keyboard input
Scanner answers = new Scanner(System.in);
//Pet objects used for calling accessor methods
Pet petName = new Pet();
Pet petType = new Pet();
Pet petAge = new Pet();
Pet petWeight = new Pet();
//A bunch of other code and pet attributes
//Input for the weight of pet
System.out.print("How many pounds does your pet weight? ");
lbs = answers.nextDouble();
petName.setWeight(lbs);
//Print out of the user's answers
System.out.println("");
System.out.println("You have a "+ petType.getType() + ". That is named "
+ petName.getName()+ " and is "
+ petAge.getAge() + " years old and weighs "
+ petWeight.getWeight() + " lbs.");
}
}
Here is my Pet Class
public class Pet
{
private String name;
private String type;
private int age;
private double weight;
/*
* a bunch of other code
*/
public void setWeight(double petWeight)
{
weight = petWeight;
}
/*
* a bunch of other code
*/
public double getWeight()
{
return weight;
}
}
the wrong is that you use this code for setting value
petName.setWeight(lbs);
and use this for retrieving value
Pet petWeight = new Pet();
they are 2 different objects you must use the same object for 2 statements in setting , retrieving
by putting
petWeight.setWeight(lbs);
instead of
petName.setWeight(lbs);
will solve it
The first important thing to this problem is that you only need one instance of the class "Pet". One pet can hold all the variables you need.
For example:
Pet pet = new Pet();
System.out.print("How many pounds does your pet weight? ");
lbs = answers.nextDouble();
petName.setWeight(lbs);
System.out.println("");
System.out.println("You have a "+ pet.getType() + ". That is named "
+ pet.getName()+ " and is "
+ pet.getAge() + " years old and weighs "
+ pet.getWeight() + " lbs.");
The way you have written it essentially creates 4 different containers when you only need one. You assigned the weight to the petWeight container but then tried to get the weight from the petName container, which resulted in you retrieving the wrong variable. With only one container, or instance, called "pet" in this case, this issue shouldn't occur.
If the age or weight doesn't have the expected formatting, I would recommend checking the return type of getAge() and getWeight. If it doesn't match the field, it will be converted when returned, at least in the int->double case (I believe double->int would require a cast).
But as already mentioned, adding .0 is the expected behaviour for double. If you don't want it, you can explicitly cast to int.
The problem I'm seeing is you are creating multiple Pet objects and assign the pet weight to the "petName" object but then you are trying to add to the output the Weight of the "petWeight" object.
Try with the following:
//Input for the weight of pet
System.out.print("How many pounds does your pet weight? ");
lbs = answers.nextDouble();
petWeight.setWeight(lbs);
//Print out of the user's answers
System.out.println("");
System.out.println("You have a "+ petType.getType() + ". That is named "
+ petName.getName()+ " and is "
+ petAge.getAge() + " years old and weighs "
+ petWeight.getWeight() + " lbs.");
}
}
Also, I would recommend to use only one object "pet" and assign every value to that one, as well as using only that one on the system.out
The problem is at line 34, check what are you doing here
petName.setWeight(lbs);
But when you show the output
System.out.println("You have a "+ petType.getType() + ". That is named "
+ petName.getName()+ " and is "
+ petAge.getAge() + " years old and weighs "
+ petWeight.getWeight() + " lbs.");
Do you see it? You are showing the wieight of "petWeight but the scanner is setting the petName object, please debug and checkout that.
System.out.print("How many pounds does your pet weight? ");
lbs = answers.nextDouble();
petWeight.setWeight(lbs);
And the result is
You have a null. That is named null and is 0 years old and weighs 1.5 lbs.
Of courst the other attributes are null.
I hope this useful. Regards!
Thanks everyone for the help. I feel like an idiot for having such a simple mistake. I also simplified my code with only one instance of pet class.
import java.util.Scanner;
public class PetAssignment {
public static void main(String[] args)
{
String nameAndType;
int yrs;
double lbs;
//Scanner object for the keyboard input
Scanner answers = new Scanner(System.in);
//Pet objects used for calling accessor methods
Pet pet = new Pet();
//A bunch of other code and pet attributes
//Input for the weight of pet
System.out.print("How many pounds does your pet weight? ");
lbs = answers.nextDouble();
pet.setWeight(lbs);
//Print out of the user's answers
System.out.println("");
System.out.println("You have a "+ pet.getType() + ". That is named "
+ pet.getName()+ " and is "
+ pet.getAge() + " years old and weighs "
+ pet.getWeight() + " lbs.");
}
}
You are doing wrong in setting and getting the weight of yours Pet. You need to use the same object to set and get value. You are setting your Pet weight in petName object and getting from petWeight object. That's why you are getting 0.0 which is the default value of double. To solve your problem
use same object to set and get your Pet's weight.
Example:
petWeight.setWeight(lbs); //setting the value in petWight object
petWeight.getWeight(); // it will returns the same value that you set.
I want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried writing
System.out.println("If you take" + stepsOne * firstNum + "steps in a 10 second interval, you could potentially achieve...");
and just about every variation I can think of but I keep getting error messages. Apparently javac hates me for some reason. :/
Also, whenever the greeting displays, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
Here's my code:
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
int firstNum;
firstNum = 6;
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello," + userName + ". How many steps do you take in a ten second interval?");
String stepsOne = userInputScanner.nextLine();
System.out.println("If you take" + stepsOne + "steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute:");
System.out.println ("Number of steps per hour:");
}
}
There is a crucial difference between the string 123 and the integer 123 - the first is merely a sequence of characters, which have no mathematical meaning. You need to parse the string, meaning that you must construct an integer based on the characters of the string. There's a built-in method for this (although it's very interesting to do it yourself too): Integer.parseInt().
String stepsOneString = userInputScanner.nextLine();
int stepsOne = Integer.parseInt(stepsOneString);
Now, stepsOne is an integer on which you can perform mathematical operations. However, Integer.parseInt() throws an exception that you'll need to handle. At this point in your course, I'm guessing that you're expected to use the built-in conversion capabilities of the Scanner:
int stepsOne = userInputScanner.nextInt();
This will essentially perform the two above steps for you.
I strongly recommend that you read up on the subject of data types, which will explain the above concepts.
Once you have a string representing a number, you can use Integer.parseInt() to get an integer from it.
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
Here is a complete program with improved spacing.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine(); //Asks user name
System.out.println("Hello, " + userName +
". How many steps do you take in a ten second interval?");
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
System.out.println("If you take " + steps +
" steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + (6 * steps));
System.out.println ("Number of steps per hour: " + (60 * 6 * steps));
}
}
Basically, I just want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried typing
First problem is stepsOne is String, so it can't be used to perform arithmetic on (at least not they type you're trying). So you need to convert it to a int
int stepsOneInt = Integer.parseInt(stepsOne);
nb: This will throw a NumberFormatException if the String can't be converted to a int value, so beware of that
Now you can use it to perform other arithmetic tasks
System.out.println("If you take " + (stepsOneInt * firstNum) + " steps in a 10 second interval, you could potentially achieve...");
Also, whenever the greeting displays in javac, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
That's because you don't add any spaces before you print the value
System.out.println ("Hello, " + userName + ". How many steps do you take in a ten second interval?");
Not sure to understand your issue...
You can't do stepsOne*firstNum as stepsOne is a String.
If stepsOne must be an int, just do this:
int stepsOne = userInputScanner.nextLine(); //Asks user a nb
I have a problem the output is supposed to be double but instead it is string
I am trying to add two double values but it is giving it as a string. I am using eclipse. Currently the program is compiling and running. If anyone have a moment I would appreciate it.Cheers guys. Here is the source code.
import java.util.Scanner;
public class FutureInvestment
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
double investmentAmount = input.nextDouble();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years: ");
int numberOfYears = input.nextInt();
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate), numberOfYears * 12));
System.out.println("Accumulated value is: " + futureInterestValue + investmentAmount);
}
}
You need to format your output. You can use DecimalFormat or you can try the String#format function:
System.out.println(
String.format("Accumulated value is: %.2f",
futureInterestValue + investmentAmount));
So you can get the 2 decimal output. Plus, I recommend to create a variable with your result, so you can turn your code into
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println(
String.format("Accumulated value is: %.2f", accumulatedValue);
Since you're doing it in a println, it's doing string concatenation. If you want to add the double's together, you need to group them using ().
Try
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println("Accumulated value is: " + accumulatedValue);
Try this.
You were getting String as result of concatenation, since anything concatenated to a string is converted to string. Therefore, you need to complete the value beforehand as I shown above, or you need parentheses.
I think change it to this would work:
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate / 100), numberOfYears * 12));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
you are missing some brackets, so your statement gets executed from left to right, thus appending the double to the string. You would need something like:
System.out.println("Accumulated value is: " + (futureInterestValue +
investmentAmount));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
After the first +, Java has concatenated the first string with the first double, resulting in a string. Then it does another concatenation with the second double. You need to calculate the result first before making a string out of it.
When two operators could be evaluated within a line of code, they do so with a fixed precedence. While this example has been explained by many, you might want to review all of the precedence rules.
You can try:
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
or add a variable like double accumulatedValue=futureInterestValue + investmentAmount;
and then System.out.println("Accumulated value is: " + accumulatedValue);
The problem is your number is getting way too large, and Java switches over to scientific notation when printing the value.
If your monthly interest rate is entered as 4.25 (meaning 4.25%), you have to convert that to the correct decimal representation of 0.0425 before using it in your calculations - you have to divide it by 100. If you don't, the interest rate used will be much larger than you intended; in this case 425%.
In other words, change
double monthlyInterestRate = input.nextDouble();
to
double monthlyInterestRate = input.nextDouble()/100;