@
@
@Qubbed2020-06-04 20:40:28
Java
@Qubbed, 2020-06-04 20:40:28

How to make the program not crash when entering words, but display an inscription?

How to do in my program (I'll attach the code at the end), when you enter words instead of numbers, the program in response displays the phrase: "You must enter numbers." The code of the program itself:

package ffd;
import java.util.Scanner;
public class MaxMin {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    while(true) {  
    System.out.println("Введите два любых числа");
    Scanner sc = new Scanner(System.in);
    float i1 = sc.nextFloat();
    float i2 = sc.nextFloat();
    String str = sc.nextLine();
    
      System.out.println("Большее из ваших чисел: " + Math.max(i1, i2));
    System.out.println("Меньшее из ваших чисел: " + Math.min(i1, i2));
    System.out.println("При сложении ваши числа дают: " + (i1+i2));
    System.out.println("При вычитании ваши числа дают: "+ (i1-i2));
    System.out.println("При умножении ваши числа дают: " + (i1*i2));
    System.out.println("При делении ваши числа дают: " + (i1/i2));
    if (i1 == 228) {
      System.out.println("Шо?");
    } else if (i2 == 228) {
      System.out.println("Шо?");
    } 
    
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OneDollarMan, 2020-06-04
_

Initially read the string, then parse it into a float, catching the NumberFormatException with a try-catch construct. In this case, if the user enters letters, the program displays a warning and continues to work.
packageffd;
import java.util.Scanner;
public class MaxMin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Enter any two numbers");
float i1 = 0;
float i2 = 0;
try {
String str1 = sc.nextLine(); //read string
i1 = Float.parseFloat(str1); //parse into float
String str2 = sc.nextLine();
i2 = Float.parseFloat(str2);
System.out.println("The largest of your numbers is: " + Math.max(i1, i2));
System.out.println("The smallest of your numbers: " + Math.min(i1, i2));
System.out.println("When added, your numbers give: " + (i1+i2));
System.out.println("When subtracted, your numbers give: "+ (i1-i2));
System.out.println("When multiplied, your numbers give: " + (i1*i2));
System.out.println("When divided, your numbers give: " + (i1/i2));
if (i1 == 228) {
System. out. println("Who?");
} else if (i2 == 228) {
System.out.println("Who?");
}
} catch(NumberFormatException e) {
System.out.println("Numbers must be entered!");
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question