Today started learning Java and I need help to clear my doubt.
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Scanner leo = new Scanner(System.in);
double f, s;
System.out.println("Enter first number: ");
f = leo.nextDouble();
System.out.println("Enter second number: ");
s = leo.nextDouble();
System.out.println("The sum is " + f + s);
}
}
When I write +f+s then both are treated as String.
Enter first number: 2
Enter second number: 5
The sum is 2.05.0
But when I write (f+s) then they are treated as doubles (which is the desired result).
Enter first number: 3
Enter second number: 4
The sum is 7
Why does that happen?
Also why do we write the line import java.util.Scanner before the class JavaAapplication1?
P.S. Is this series of videos Video Link good for learning Java?
I suspect that what matters is the order of operation
In
System.out.println("The sum is:"+f+s)
The first operation is "The sum is:"+f so the + operator takes a string and a double as operands and the f variable is cast to its string value. Then second + operator takes "The sum is:2"+0.5 and again we have a conversion from double to string.
However, in
System.out.println("The sum is:"+(f+s))
We first have f+s calcualted which is an addition between two doubles followed by a concatenation.
I hope this makes sense.
It is the BODMAS rule which stands for Brackets, Orders, Division, Multiplication, Addition, Subtraction
Since you dont add them in brackets, it adds(concatenates) the string. It evaluates everything within the bracket
("string" + f + s)
Unless you specifically add brackets
("string" + (f + s))
In this case, the inner brackets are evaluated first and then the outer.
Also why do we write the line import java.util.scanner before the
class java application 1?
In order to use the imported stuff in the class, you need to import before class, so the compiler knows.
Related
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
This question already has answers here:
Why Wont My Java Scanner Take In input?
(3 answers)
Closed 7 years ago.
When I run my code, it works right up until it asks the question "which operation do you want to use from ( sum , subst , multi , div )". No matter what the user picks, there is no response from my program!
Why is this happening?
import java.util.Scanner;
import java.io.*;
public class three3 {
public static void main (String[] args) {
int x;
int y;
int opera;
String oper;
Scanner in = new Scanner (System.in);
System.out.println(" write the first number ");
x = in.nextInt();
System.out.println(" write the second number ");
y = in.nextInt();
System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
oper = in.nextLine();
if (oper == "sum") {
opera=x+y;
System.out.println(" the sum of two numbers is " + opera );
}
if (oper == "subst") {
opera = x - y;
System.out.println(" the subtraction of two numbers is " + opera );
}
if (oper == "multi") {
opera = x * y;
System.out.println(" the multi of two numbers is " + opera );
}
if (oper == "div") {
opera = x / y;
System.out.println(" the division of two numbers is " + opera );
}
}
}
Because none of those if-clauses is executed.
You're comparing Strings with == which is wrong. Use oper.equals("sum") instead. See this question for reference. The conclusion for you is to always use equals for Strings.
You need to call in.nextLine() right after the last call to in.nextInt() The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine().
int y = in.nextInt();
in.nextLine();
This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line, such as when you call nextBoolean() etc.
In addition, you don't check for String equality with the == operator, use the .equals() String method instead.
The problem is that in.nextLine() consumes the \n inserted implicitly when you clicked enter after the int was entered. That means that the program doesn't expect any other input from the user. To fix this you could consume a new line with in.nextLine() before putting it int your actual variable, something like this:
System.out.println(" write the second number ");
y=in.nextInt();
System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
in.nextLine(); //New line consuming the \n
oper=in.nextLine();
if(oper.equals("sum")){//replace == by .equals
opera=x+y;
}
Apart from that, and as runDOSrun said, you should replace the comparisons of strings from a==b to a.equals(b)
Adding on to other people's points, you should also consider using else if{} and else{} statements so you can catch invalid input.
I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
But I can't get the user to write a string and an int. Do I need to say String answer or int answer?
An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.
On a simpler side, String will be required input from the user, User will enter the equation.
Then comes the complex part of solving/computing the equation.
1.) create your own parser to pass operands/operator.
2.) Provide a equation with values to some API, you can make use of MVEL or ANTLR
Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.
import java.util.Scanner;
public class SolveX{
public static void main(String[] a){
Scanner in = new Scanner(System.in);
System.out.println("Write an equation and I will solve for x.");
String input = "";
while( in.hasNext() ){
input = in.next();
try{
double d = Double.parseDouble(input);
System.out.println("Double found at: " + input);
// Do what you need to with the numeric value
}
catch(NumberFormatException nfe){
System.out.println("No double found at: " + input);
// Do what you need to with the non numeric value
}
}
}//end main
}//end SolveX class
I am trying to get java to display the middle digit of a 1-4 digit integer, and if the integer has an even number of digits i would get it to display that there is no middle digit.
I can get the program to take get the integer from the user but am pretty clueless as how to get it to pick out the middle digit or differentiate between different lengths of integer.
thanks
Hint: Convert the integer to a String.
Java int to String - Integer.toString(i) vs new Integer(i).toString()
You may also find the methods String.length and String.charAt useful.
This sounds like it might be homework, so I will stay away from giving an exact answer. This is much more about how to display characters than it is about integers. Think about how you might do this if the questions was to display the middle letter of a word.
Something like this?
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (!s.hasNextInt()) {
s.next();
System.out.println("Please enter an integer.");
}
String intStr = "" + s.nextInt();
int len = intStr.length();
if (len % 2 == 0)
System.out.println("Integer has even number of digits.");
else
System.out.println("Middle digit: " + intStr.charAt(len / 2));
}
}
Uhm, I realized I might just have done someones homework... :-/ I usually try to avoid it. I'll blame the OP for not being clear in this case
So I have looked at a couple of related questions, but still can't seem to find my answer (I guess because it's specific). I'm trying to use the Scanner.useDelimiter method in Java and I can't get it to work properly... here is my dilemma...
We are supposed to write a program that takes a X, Y coordinate and calculates the distance between the two points. Obviously, one solution is to scan for each x and y coordinate separately, but this is sloppy to me. My plan is to ask the user to input the coordinate as "x, y" and then grab the integers using the Scanner.nextInt() method. However, I have to find a way to ignore the "," and of course, I can do that with the useDelimiter method.
According to other threads, I have to understand regex (not there yet) to put in the useDelimiter method and I've got it to ignore the commas, HOWEVER, there is a possibility that a user inputs a negative number as a coordinate (which is technically correct). How do I get useDelimiter to ignore the comma, but still recognize the negative sign?
This is my first time on here, here is my code:
import java.util.Scanner;
import java.text.DecimalFormat;
public class PointDistanceXY
{
public static void main(String[] args)
{
int xCoordinate1, yCoordinate1, xCoordinate2, yCoordinate2;
double distance;
// Creation of the scanner and decimal format objects
Scanner myScan = new Scanner(System.in);
DecimalFormat decimal = new DecimalFormat ("0.##");
myScan.useDelimiter("\\s*,?\\s*");
System.out.println("This application will find the distance between two points you specify.");
System.out.println();
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
xCoordinate1 = myScan.nextInt();
yCoordinate1 = myScan.nextInt();
System.out.print("Enter your second coordinate (format is \"x, y\"): ");
xCoordinate2 = myScan.nextInt();
yCoordinate2 = myScan.nextInt();
System.out.println();
// Formula to calculate the distance between two points
distance = Math.sqrt(Math.pow((xCoordinate2 - xCoordinate1), 2) + Math.pow((yCoordinate2 - yCoordinate1), 2));
// Output of data
System.out.println("The distance between the two points specified is: " + decimal.format(distance));
System.out.println();
}
}
Thanks for your help and I look forward to helping other people down the line!
I think it would be easier (and more conventional for the command line type of programs) to just ask for x and y separately
Example:
Scanner myScan = new Scanner(System.in);
System.out.print("Enter your first x coordinate: ");
xCoordinate1 = Integer.parseInt(myScan.nextLine());
yCoordinate1 = Integer.parseInt(myScan.nextLine());
However if you insist on doing both at the same time and using a delimeter you could try using the return line as a delimeter instead of the ", " because you would have to delimit it twice remember, once after x and then again after y. But that sort of brings you back to the same result. The problem is that you need to delimit it twice if you want to use a delimeter and take it in at the same time. I'd suggest taking a look at the .split function of a string instead.
Another approach would be to use the .split(", "); function where ", " is your delimiter.
Example:
Scanner myScan = new Scanner(System.in);
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
String input = myScan.nextLine();
xCoordinate1 = Integer.parseInt(input.split(", ")[0]);
yCoordinate1 = Integer.parseInt(input.split(", ")[1]);
Hope this helps, Enjoy.