import java.util.Scanner; public class Main { public static void main(String[] args) {…
- User
import java.util.Scanner;
public class Main {
codepublic static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Adj meg két számot (vesszővel elválasztva): "); int sz1=0, sz2=1; //sz1 = sc.nextInt(); //sz2 = sc.nextInt(); String input = sc.nextLine(); String[] darabok = input.split(","); if (darabok.length != 2) { System.err.println("Nem két, vesszővel elválaszott számot adtál meg."); return; } try { //probald meg futtatni, ha nem sikerul, ugorj a catche-re. sz1 = Integer.parseInt(darabok[0]); sz1 = Integer.parseInt(darabok[1]); } catch (NumberFormatException e) { System.err.println("Legalább az egyik szám nem szám."); e.printStackTrace(); } System.out.println("A beírt két szám: " + sz1 + ", " + sz2); System.out.println("A két szám hányadosa: " + sz1/sz2); System.out.println("A program végig lefutott."); }}
why doesn't it converts my numbers
- Assistant
Your code correctly parses the input strings to integers but has a logical mistake in reassigning the values. The value of
sz2is not being updated correctly with the input. In the try block, you are mistakenly reassigningsz1with the second number from the input array instead of assigning it tosz2.Here is the corrected section:
javatry { //probald meg futtatni, ha nem sikerul, ugorj a catche-re. sz1 = Integer.parseInt(darabok[0].trim()); // Trim to remove any whitespace sz2 = Integer.parseInt(darabok[1].trim()); // Fixed this line } catch (NumberFormatException e) { System.err.println("Legalább az egyik szám nem szám."); e.printStackTrace(); }