Please note the print statements, in the code segments below. My question is how come If I try to add two doubles in the print statement it prints incorrectly, but if I add them outside the print statement and store the result in a variable than I am able to print it correctly.
Why does this work and print out the correct result?
public static void main(String argsp[]){
Scanner input = new Scanner(System.in);
double first, second, answer;
System.out.println("Enter the first number: ");
first = input.nextDouble();
System.out.println("Enter the second number: ");
second = input.nextDouble();
answer = first + second;
System.out.println("the answer is " + answer);
}
Why does this print out the wrong result?
public static void main(String argsp[]){
Scanner input = new Scanner(System.in);
double first, second;
System.out.println("Enter the first number: ");
first = input.nextDouble();
System.out.println("Enter the second number: ");
second = input.nextDouble();
System.out.println("the answer is " + first+second);
}
It's because what you're basically doing in that second part is:
System.out.println("the answer is " + String.valueOf(first) + String.valueOf(second));
That's how the compiler interprets it. Because the + operator when you are giving a String to a method is not a calculation but a concatenation.
If you want it done in one line, do it like this:
System.out.println("the answer is " + (first + second)); //Note the () around the calculation.
In case of doubt with the precedence of operators, just use parens. It is also clearer to read.
System.out.println("the answer is " + (first+second));
In the second case, the doubles are converted to Strings because the + is considered String concatenation. To work around this, use parentheses to group expressions that should perform numeric calculations:
System.out.println("the answer is " + (first + second));
Related
I am new to java and I wrote a Basic Input/Output program and in this program I want the user to provide 3 different inputs and be saved in 3 different variables, they are two int and one char.
public static void ForTesting() {
Scanner newScanTest = new Scanner(System.in);
ٍٍٍٍٍٍٍٍٍٍٍSystem.out.print("Please type two numbers: ");
int numberOne = newScanTest.nextInt();
int numberTwo = newScanTest.nextInt();
System.out.println("First Nr.: " + numberOne + " Second Nr.: " + numberTwo);
}
In the consol
What I get:
Please type two number: 4
5
First Nr.: 4 Second Nr.: 5
What I want:
Please type two number: 4 5
First Nr.: 4 Second Nr.: 5
(The bold numbers are the user input)
nextLine(), as the name suggests, reads a single line. If both numbers are contained on this single line, you should read both integers from that line. For example:
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine(); // reads the single input line from the console
String[] strings = line.split(" "); // splits the string wherever a space character is encountered, returns the result as a String[]
int first = Integer.parseInt(strings[0]);
int second = Integer.parseInt(strings[1]);
System.out.println("First number = " + first + ", second number = " + second + ".");
Note, this will fail if you don't provide 2 integers in the input.
Please try the bellow code, i try to convert integers to strings.
public static void ForTesting() {
Scanner newScanTest = new Scanner(System.in);
ٍٍٍٍٍٍٍٍٍٍٍSystem.out.print("Please type two numbers: ");
int number = newScanTest.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
int secondDigit = Integer.parseInt(Integer.toString(number).substring(1, 2));
System.out.println("First Nr.: " + firstDigit + " Second Nr.: " + secondDigit);
}
If you are very sure about input like (2+2) or (2-2) or (2*2) or (2/2)
below should work -
Scanner scanner = new Scanner(System.in);
Integer first = scanner.nextInt();
String operator = scanner.next();
Integer second = scanner.nextInt();
System.out.println("First number = " + first + ", second number = " + second + ".");
I have a prompt to "Write a program that performs the following operations: +, -, *, /, % (as defined by Java). Your program should first read the first number, then the operation, and then the second number. Both numbers are integers. If, for the operation, the user entered one of the symbols shown above, your program should perform the corresponding operation and compute the result. After that it should print the operation and the result. If the operation is not recognized, the program should display a message about it. You do not need to do any input validation for the integers."
An example output I'm given is:
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
How can I get started on this? I'm super confused and really new to java! Any help is greatly appreciated.
You generally first want to start reading input from STDIN:
Scanner in = new Scanner(System.in);
Then, I would read all parameters and afterwards perform the computation:
System.out.print("Enter the first number: ");
int left = Integer.parseInt(in.nextLine());
System.out.print("Enter the operation: ");
String operation = in.nextLine();
System.out.print("Enter the second number: ");
int right = Integer.parseInt(in.nextLine());
Now that all input is collected, you can start acting.
int result;
switch(operation)
{
case "+": result = left + right; break;
case "-": result = left - right; break;
case "*": result = left * right; break;
case "/": result = left / right; break;
case "%": result = left % right; break;
default: throw new IllegalArgumentException("unsupported operation " + operation);
}
System.out.println(left + " " + operation + " " + right + " = " + result);
Sounds like we are doing your homework! :) Make sure you learn these things or else it will eventually bite you. You can only delay the inevitable. With that "fatherly advice", here ya go.
First, you need to be able to read input from the console so that you can get the input numbers and operation. Of course, there are whole answers on this already. One link:
Java: How to get input from System.console()
Once you have the input, then you can work with it.
You will need to look at the items entered. They say you don't need to validate the numbers but you need to validate the operation. So look at the operation String variable after you got it from the console and see if it is "equalsIgnoreCase" (or just equals since these symbols don't have uppercase) to each one of the accepted operations. If it isn't equal to any of them then you should print out a message as it says. (Again with System.out.println).
You can then go into some if conditions and actually do the math if the operation equals one of the items. For example:
if(inputOperation.equalsIgnoreCase("+")){
double solution = inputInt1 + inputInt2;
//Need to do for all other operations. I didn't do the WHOLE thing for you.
}else if(NEED_TO_FILL_IN_THIS){
//Need to fill in the operation.
//You will need to have more else if conditions below for every operation
}else{
System.out.println("Your operation of '"+inputOperation+"' did not match any accepted inputs. Accepted input operations are '+','-','%','/' and '*'. Please try again.");
}
System.out.println("Your answer to the equation '"+inputInt1+" "+inputOperation+" "+inputInt2+"' is the following:"+solution);
That should get you started. Let me know if you still need further direction.
I hope that helps!
And to end with some fatherly advice: Again, it sounds like you are doing homework. This is all pretty well documented if you just know how to google. "Java get input from console". Or "Java check if String is equal to another string". Learning how to fish is so much more important than getting the fish. I suggest you do some catchup because if this is your homework and you are unsure then it seems like you are a bit behind. I don't mean to be rude. I am just trying to help you longer term.
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
Scanner f=new Scanner(System.in)
System.out.print("Enter the first number: ")
int firstNum=f.nextInt();
System.out.println();
System.out.print("Enter the operation: ")
String Op=f.nextLine();
System.out.println();
System.out.print("Enter the Second number: ")
int secNum=f.nextInt();
System.out.println();
int answ=0;
if(Op.equals("+"){
answ=firstNum+secNum;
}else if(.......){
}
hope it helps :)
To read the integers, use a Scanner
public static void main(String [] args)
{
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the first number: ");
int firstNum = stdin.nextInt(); //first number
System.out.println("Enter the operation: ");
String operation = stdin.next(); //operation
System.out.println("Enter the second number: ");
int secondNum = stdin.nextInt(); //second number
doOperation(firstNum, secondNum, operation);
}
public static void doOperation(int firstNum, int secondNum, String operation)
{
if(operation.equals("+")
{
int result = firstNum + secondNum;
}
else if(...)
{
//etc
}
System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result);
}
Here is My Solution
package com.company;
import com.sun.org.apache.regexp.internal.RE;
import java.util.Scanner;
public class Main {
private static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
// write your code here
int First,Second,Resualt;
char operation;
System.out.println("Enter the first number: ");
First=scanner.nextInt();
System.out.println("Enter the operation:");
operation=scanner.next().charAt(0);
System.out.println("Enter the second number :");
Second=scanner.nextInt();
if (operation=='+'){
Resualt=First+Second;
System.out.println(First+" "+"+ "+Second+" = "+Resualt);
}
else if (operation=='-'){
Resualt=First-Second;
System.out.println(First+" "+"- "+Second+" = "+Resualt);
}
else if (operation=='*'){
Resualt=First*Second;
System.out.println(First+" "+"* "+Second+" = "+Resualt);
}
else if (operation=='%'){
Resualt=First%Second;
System.out.println(First+" "+"% "+Second+" = "+Resualt);
}
else {
System.out.println("Error");
}
}
}
Good Luck!!
I have a basic java question about the scanner utility. Let's say i have a simple program that takes the user input and stores it in a variable. My question is when i run the program that asks for multiple inputs, the cursor starts at the beginning of the question and not after it.
My code is:
public class question3 {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the first number:");
Float a = s.nextFloat();
System.out.println("Enter the second number:");
Float b = s.nextFloat();
System.out.println("Sum = " + (a+b));
System.out.println("Difference = " + (a-b));
System.out.println("Product = " + (a*b));
}
}
When I run this program it will look like Enter First Number then i type the number, and then |Enter Second Number. "|" meaning where the blinking cursor is. When I type it'll show up underneath, but it could confuse the user so I was wondering what the solution could be.
It is an IDE problem, since nothing else is wrong with the code.
Instead of println(String) before each input, change it to print(String). So it would look something like this:
public class question3{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
Float a = s.nextFloat();
System.out.print("Enter the second number:");
Float b = s.nextFloat();
System.out.println("Sum = " + (a+b));
System.out.println("Difference = " + (a-b));
System.out.println("Product = " + (a*b));
}
}
Also, just a note, you should use proper/appropriate naming conventions for your variables. Like for your Scanner, you should call it reader or input; something which represents its function. The same idea goes for the rest of your variables. Also, class names start with a capital.
Here is what the finished result looks like:
System.out.println prints out string then a new line, so your input is being placed on a new line. Try making it read
System.out.print("Enter the first number:");
Float a = s.nextFloat();
System.out.println();
System.out.print("Enter the second number:");
Float b = s.nextFloat();
System.out.println();
This can save you some seconds, by typing few lines:
System.out.print("Enter the first number:");
Float a = s.nextFloat();
System.out.print("\nEnter the second number:");
Float b = s.nextFloat();
System.out.println("\nSum = " + (a+b)
+"\nDifference = " + (a-b)
+"\nProduct = " + (a*b));
I'm supposed to make a program that continuously accepts desk order data and displays all the relevant information for oak desks that are over 36 inches long and have at least one drawer.
import java.util.*;
public class MangMaxB
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
char ans;
int orderNum=0, length=0, width=0, numDrawer=0, price=1000;
String name;
System.out.print("Do you wish to enter Oak " +
"desk order data? (y/n)");
ans = input.nextLine().charAt(0);
while (ans != 'n')
{
System.out.print("Enter customer name: ");
name=input.nextLine();
System.out.print("Enter order number: ");
orderNum=input.nextInt();
System.out.print("Enter length and width of Oak desk" +
" separated by a space: ");
length = input.nextInt();
width = input.nextInt();
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
if ((length>36)&&(numDrawer>=1))
{
if ((length*width)>750)
{
price+= 250;
}
price+= (numDrawer*100);
price+= 300;
System.out.println("\nOak desk order information:\n"
+ "Order number: " + orderNum + "\n"
+ "Customer name: " + name + "\n"
+ "Length: " + length + ", width: "
+ width + ", surface: " + (length*width)
+ "\n" + "Number of drawer/s: " + numDrawer
+ "\nPrice of the desk is P " + price);
}
else
{
System.out.println("\nOak desk order isn't over 36 " +
"inches long and doesn't have a drawer");
}
System.out.print("Any more items? (y/n) ");
ans = input.nextLine().charAt(0);
}
}
}
I was able to enter data and display it but on the second attempt since it is a loop, it didn't work.
It says "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at controlStruc.MangMaxB.main"
how do I fix this?
nextInt() doesn't read the end of the line - just the next integer. You need to call nextLine() after nextInt() if you want to read the remainder of that line.
At present, you're not doing so, so the last nextLine() method just reads the rest of the empty line after the integer, and returns immediately with an empty string, causing the exception.
In this case, putting a nextLine() call here should do the trick:
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
input.nextLine(); //Added nextLine() call
Please use like the below,
System.out.print("Any more items? (y/n) ");
input = new Scanner(System.in);
ans = input.nextLine().charAt(0);
beacuse input.nextLine() returns empty string, so when try to get 0th char it returns StringIndexOutOfBoundsException
You need to get a String before calling input.nextLine()
Are you just pressing enter?
ans = input.nextLine().charAt(0);
is throwing this error when it's an empty string. Your exception is clearly telling you this. You need to check if the "nextLine" is an empty string or not.
Clearly according to documentaion:
nextLine()-Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
nextInt()-Scans the next token of the input as an int.
And henceforth ans = input.nextLine() in your code is returning you with '' and char(0) leading for StringIndexOutOfBoundsException.
read 2 numbers and determine whether the first one is a multiple of second one.
if (first % second == 0) { ... }
Given that this is almost certainly a homework question...
The first thing you need to think about is how you would do this if you didn't have a computer in front of you. If I asked you "is 8 a multiple of 2", how would you go about solving it? Would that same solution work if I asked you "is 4882730048987" a multiple of 3"?
If you've figured out the math which would allow you to get an answer with just a pen and paper (or even a pocket calculator), then the next step is to figure out how to turn that into code.
Such a program would look a bit like this:
Start
Read in the first number and store it
Read in the second number and store it
Implement the solution you identified in paragraph two using the mathematical operations, and store the result
Print the result to the user.
//To check if num1 is a multiple of num2
import java.util.Scanner;
public class multiples {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number!");
int num1 = reader.nextInt();
reader.nextLine();
System.out.println("Enter another number!");
int num2 = reader.nextInt();
if ((num1 % num2) == 0) {
System.out.println("Yes! " + num1 + " is a multiple of " + num2 + "!");
} else {
System.out.println("No! " + num1 + " is not a multiple of " + num2 + "!");
}
reader.close();
}
}
A number x is a multiple of y if and only if the reminder after dividing x with y is 0.
In Java the modulus operator(%) is used to get the reminder after the division. So x % y gives the reminder when x is divided by y.