Java Умножение 2 целых чисел из строк

Я пытался найти несколько потоков с точки зрения умножения 2 строк. Однако, кажется, что большинство ссылок, которые я нашел, были неприменимы, или я не мог интерпретировать их достаточно хорошо.

Было бы возможно, если бы мог сказать мне, что не так с моим текущим кодом?

public static void main(String[] args) {

    String sample = value1();
    String sample2 = value2();
            //========== Test if users placed any characters within the boxes =========\\
            try {
                Integer.parseInt(sample);
            } catch (NumberFormatException e) {
                System.out.println("System detects that you are using characters");
                return;
            }
            try {
                Integer.parseInt(sample2);
            } catch (NumberFormatException e) {
                System.out.println("System detects that you are using characters");
                return;
            }
     Integer.parseInt(sample); 
     Integer.parseInt(sample2);
    System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
}

public static String value1() { //obtain first user input. 

    String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
    if (sample.isEmpty()) {

        JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
        sample = value1();


    }
    return sample;

}

public static String value2() { //obtain second user input. 

    String sample2 = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
    if (sample2.isEmpty()) {

        JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
        sample2 = value2();


    }
    return sample2;

}    

}

Мой окончательный вывод должен умножить следующие числа

System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");

4 ответа

Решение

Вы не можете умножать строки вместе. Вы можете умножать числа, и это звучит так, как будто вы хотите этого. Действительно, вы уже анализируете строки как целые числа, а затем игнорируете результат. Вам просто нужно изменить это:

 Integer.parseInt(sample); 
 Integer.parseInt(sample2);
 System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");

чтобы:

 int value1 = Integer.parseInt(sample); 
 int value2 = Integer.parseInt(sample2);
 System.out.println("The total multiplication that you have inserted is "
     + (value1 * value2) + ".");

Вы должны назначить возвращаемое значение Integer.parseInt() для переменных. Переменные, передаваемые в качестве параметра, остаются неизменными.

 int a = Integer.parseInt(sample); 
 int b = Integer.parseInt(sample2);
 System.out.println("The total multiplication that you have inserted is " + a * b + ".");

Вы пытаетесь умножить две строки, а не два числа

вы должны использовать так:

System.out.println("The total multiplication that you have inserted is "+ Integer.parseInt(sample) * Integer.parseInt(sample2)+ ".");

1-е предложение: никогда (никогда!) Не объявляйте 2 метода, которые делают одно и то же!!

public static String value() { //obtain *first and second* user input. 
  String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
  if (sample.isEmpty()) {
    JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
    sample = value();
  }
  return sample;
}

2-е предложение: не проверяйте правильность вашего ввода как в методе value(), так и в main():

public static int value() { //obtain second user input. 
  String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
  if (sample.isEmpty()) {
    JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
    return value();
  }
  try {
    int v = Integer.parseInt(sample);
    return v;
  } catch (NumberFormatException e) {
    System.out.println("System detects that you are using characters");
    return value();
  }
}

для этого второго случая основным становится:

public static void main(String[] args) {
  int x1 = value();
  int x2 = value(); // call again the *same* method

  System.out.println("The total multiplication that you have inserted is "+x1 * x2+ ".");
}
Другие вопросы по тегам