+ 4
I need a help :(
Help me with this code, please :) Why does he write "else" when entering something? (Thank you in advance) https://code.sololearn.com/cYZl54zLUGdy/?ref=app
3 Antworten
+ 18
//here is the corrected code ☺
//hope it helps
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println ("+ or -");
String user = sc.nextLine();
if (user.equals("+")){
System.out.println ("x = ");
double xxp = sc.nextDouble();
System.out.println ("y = ");
double yyp = sc.nextDouble();
double resultP = yyp + xxp;
System.out.println ("Result is: " + resultP);
}
else if (user.equals("-")){
System.out.println ("x = ");
double xxm = sc.nextDouble();
System.out.println ("y = ");
double yym = sc.nextDouble();
double resultM = yym - xxm;
System.out.println ("Result is: " + resultM);
}else {
System.out.println ("Error :(");
}
}
}
+ 7
Description; There's no benefit in creating more than one Scanner object (or instance). It simply reads input from a stream, and having more than one reference to that stream isn't necessary to your operations. You should use only one instance for every input method.
And, you might want to use the equals() instead of the comparison operator (==). Check: https://www.sololearn.com/learn/Java/2178/
+ 3
use user.equals("=") instead of user=="+"
strings in java are actually pointers and you don't want to check if they point to the same location (this is ==), but if their value is equal
the user's response is a different place in memory than the literal in your program