import java.io.*; public class HelloWorld { public static void main( String[] args ) throws NumberFormatException, IOException { String question = "y"; // чтобы вводить в строки надо создать BufferedReader BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Решение квадратного уравнения"); while( question == "y" ) { System.out.print("a = "); double a = Double.parseDouble(reader.readLine()); System.out.print("b = "); double b = Double.parseDouble(reader.readLine()); System.out.print("c = "); double c = Double.parseDouble(reader.readLine()); // Math.pow() функция возведения в степень (что, в какую степень) double d = Math.pow(b, 2) -4*a*c; // если дискриминант строго меньше нуля if (d < 0) System.out.println("Корней нет"); else if (d == 0) { double x = -b/(2*a); System.out.printf("Единственный корень x = %g\n", x); } else { double ds = Math.sqrt(d); double x1 = (-b+ds)/(2*a); double x2 = (-b-ds)/(2*a); System.out.printf("x1 = %g\nx2 = %g\n", x1, x2); } //------------------------------------------------------------------ System.out.print("Продолжить? [y/n] "); question = reader.readLine(); System.out.println("Вы выбрали: " + question); // для проверки //------------------------------------------------------------ } //цикл } }
2 answers
Opeyayayat Well, don't compare strings with ==, but use equals.
- Thank you so much! Happened!!! - Burunduk
- And how not with “String question =" y "”, but with “char = 'y'”? - Burunduk
- question = Character.parseChar (reader.readLine ()); - not working - Burunduk
- fourLearn the same languages systematically, and not on tutorials. - Nofate ♦
- oneAnd what if the channel suddenly ends? Then readLine returns null ... <br /> Aaaaaaaaaaaaaaaaaaaa .... buhhhh - cy6erGn0m
// Rule 1
// all variable values of which do not change need to be declared constants (you can replace the others yourself)
// Rule 2
// it is desirable to always use the simplest solution
// Rule 3
// Announcement of variables that are used in the chain is better to move beyond its limits
// Rule 4
// The code should be divided into logically related blocks, and provide them with comments:
// Rule 5
// if a variable is used only once, you can do without it, but it is left if the readability of the code suffers greatly
// Rule 6
// When comparing, the constant should always go to the left: (x == 5) -> (5 == x)
// Rule 7
// It's no good to throw exceptions somewhere if you can handle them on the spot
import java.util.Scanner;
public class HelloWorld {// declare constants private static final String WELCOME_STRING = "Solving a quadratic equation"; private static final String ENTER_A = "a ="; private static final String ENTER_B = "b ="; private static final String ENTER_C = "c ="; private static final String CONTINUE = "y";
public static void main (Final String [] args) {System.out.println (WELCOME_STRING);
// обьявляем все необходимые переменные final Scanner scanner = new Scanner ( System.in ); String code = CONTINUE; double a2, b, c, d, x1, x2, ds; // решаем уравнения до тех пор пока не надоест пользователю boolean oneMoreTime = true; while ( oneMoreTime ) { // считываем необходимые параметры с командной строки: System.out.println ( "Введите параметры квадратного уравнения: a*x*x + b*x + c = 0" ); System.out.print ( ENTER_A ); a2 = scanner.nextDouble () * 2; // ^^ сразу умножаем на 2, // так как введеное значение используется нашей програмой только удвоенным System.out.print ( ENTER_B ); b = scanner.nextDouble (); System.out.print ( ENTER_C ); c = scanner.nextDouble (); // считаем дискриминант уравнения d = Math.pow ( b, 2 ) - 2 * a2 * c; // Math.pow() функция возведения в степень (что, в какую степень) // ^^ 4 * a * c = 2 * (2 * a) * c // мы значение 2 * а уже подсчитали при считывании // проверяем дискриминант и выводим корни уравнения if ( 0 > d ) { System.out.println ( "Корней нет" ); } else { if ( 0 == d ) { x1 = ( -b / a2 ); System.out.printf ( "Один корень:\n\tx = %g\n", Double.valueOf ( x1 ) ); } else { ds = Math.sqrt ( d ); x1 = ( -b + ds ) / a2; x2 = ( -b - ds ) / a2; System.out.printf ( "Два корня:\n\tx1 = %g\n\tx2 = %g\n", Double.valueOf ( x1 ), Double.valueOf ( x2 ) ); } } // спрашиваем юзера нужно ли продолжать System.out.print ( "Продолжить? [y/n] " ); code = scanner.next (); oneMoreTime = code.equals ( CONTINUE ); System.out.println ( "\tВы выбрали: '" + code + "', " + ( oneMoreTime ? "продолжаем" : "выходим" ) ); System.out.println (); }
}}
- Damn convenient code formatter, I want to insert 4 spaces before each line. - jmu
- I believe that rule 3 reduces the readability of the code, and rule 6 completely rudiment from C ++, where you can accidentally type
=
instead of==
and this may go unnoticed for some time. @jmu Usually, the code is copied from the IDE, where you already have indentation, or simply add it. - AlexeyM - one2 @AlexeyM: "Typically, the code is copied from the IDE, where there is already indentation, or simply add it." The fact that I can use my IDE in no way affects the usability of the site formatter - jmu
- 2 @AlexeyM: Rule 3 - in general, this bad rule appeared when allocating memory for the next object was more costly than it is now. The readability decrease is insignificant and in development it should be compensated by the correct names of variables and comments to them. Rule 6 - everyone decides for himself whether he should adhere to it or not. I personally want to rely on my head than on the heads of IDE developers in which I work - jmu
- @jmu It's not about the IDE, but about the language specification. Java, C # and many other languages are deprived of this problem, since the conditional operator accepts exclusively bool expressions. - AlexeyM