Как мне разделить 2 слова символом «@»?

#java

#java

Вопрос:

У меня есть задание из моего университета, в котором я должен запросить у пользователя 2 числа, одно целое число, другое десятичное, и распечатать их продукт в денежном формате. Программа также должна принимать два слова, разделенные символом @. Я изо всех сил пытаюсь разобраться в последней части задачи (два слова, разделенные символом @).

Все остальное я прекрасно понимаю.

Это упражнение

 Sample run 1:
Enter a whole number: 4
Enter a decimal number: 6.854
Enter two words delimitated by @ symbol: Mango@15
  

Вывод:

 The product of the 2 numbers: 27.416
The product in money format is: N$ 27.42
Assuming the user bought 4 Mango(s) costing N$ 6.85
The VAT to be charged is 15%, hence total due to be paid is N$ 31.53
  

Это мой код.

 import java.util.Scanner;
public class Lab02_Task4 {
    public static void main(String[]args){
        Scanner info = new Scanner(System.in);
        int whole;
        System.out.println("Enter a whole number: ");
        whole = info.nextInt();
        double decimal;
        System.out.println("Enter a decimal number: ");
        decimal = info.nextDouble();
        String item;
        System.out.println("Enter two words delimitated by @ symbol: ");
        item = info.nextLine();
        
        String item2 = "Mango";
        double total = whole * decimal;
        double vatIncluded = (total * 0.15)   total;
        String s=String.valueOf(total);
        System.out.println("The product of the 2 numbers: "   total);
        String total2 = String.format("%.2f", total);
        System.out.println("The product in money format is: N$ "   (total2));
        String vatIncluded2 = String.format("%.2f", vatIncluded);
        System.out.println("Assuming the user bought "   whole   " "    item2   "(s) "   "costing N$ "   total2   
" The VAT to be charged is 15%, hence total due to be paid is N$ "   vatIncluded2);
    }
}
  

Комментарии:

1. Что вы хотите сделать с этим @item ?

2. Я понял. Слово перед @ — это элемент, а число после @ — это «налог» или, в данном случае, НДС. Пожалуйста, исправьте, если я ошибаюсь.

3. Разделитель может быть правильной формой разделителя , но форма, которую я видел чаще всего в отношении информатики, является разделителем .

4. используйте split() или регулярное выражение, если хотите

Ответ №1:

Вы можете использовать split для разделения двух значений следующим образом:

 public static void main(String[] args) {
  String string = "value@anothervalue";
  String[] arr = string.split("@");
  System.out.print(Arrays.toString(arr)); //[value, anothervalue]
}
  

Ответ №2:

Это поможет:

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int wholenumber = Integer.parseInt(input.nextLine());
    double decimal = Double.parseDouble(input.nextLine());
    String[] deli = input.nextLine().split("@");
    String item = deli[0];
    int tax = Integer.parseInt(deli[1]);
    double product = decimal*wholenumber;
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String rounded = formatter.format(product).substring(1);
    double finalprice = product*tax/100 product;
    System.out.println("The product of the 2 numbers: " product);
    System.out.println("The product in money format is: N$" rounded);
    System.out.println("Assuming the user bought " wholenumber " " item "s costing N$" formatter.format(decimal).substring(1));
    System.out.println("The VAT to4 be charged is " tax "%, hence the total due to the paid is N$" finalprice);
    //The VAT to be charged is 15%, hence total due to be paid is N$ 31.53
}
  

Пример запуска

 4
6.854
Mango@15
The product of the 2 numbers: 27.416
The product in money format is: N$27.42
Assuming the user bought 4 Mangos costing N$6.85
The VAT to4 be charged is 15%, hence the total due to the paid is N$31.5284
  

С помощью пользовательских подсказок

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int wholenumber = Integer.parseInt(input.nextLine());
    System.out.print("Enter a decimal number: ");
    double decimal = Double.parseDouble(input.nextLine());
    System.out.print("Enter two words seperated by @ symbol: ");
    String[] deli = input.nextLine().split("@");
    String item = deli[0];
    int tax = Integer.parseInt(deli[1]);
    double product = decimal*wholenumber;
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String rounded = formatter.format(product).substring(1);
    double finalprice = product*tax/100 product;
    System.out.println("The product of the 2 numbers: " product);
    System.out.println("The product in money format is: N$" rounded);
    System.out.println("Assuming the user bought " wholenumber " " item "s costing N$" formatter.format(decimal).substring(1));
    System.out.println("The VAT to4 be charged is " tax "%, hence the total due to the paid is N$" finalprice);
    //The VAT to be charged is 15%, hence total due to be paid is N$ 31.53
}
  

Пример запуска

 Enter a number: 4
Enter a decimal number: 6.854
Enter two words seperated by @ symbol: Mango@15
The product of the 2 numbers: 27.416
The product in money format is: N$27.42
Assuming the user bought 4 Mangos costing N$6.85
The VAT to4 be charged is 15%, hence the total due to the paid is N$31.5284