[英]How to take multiple data types in single line on java?
我是編碼新手,現在我正在學習 Java。 我試着寫一些類似計算器的東西。 我用 switch case 編寫了它,但后來我意識到我必須將所有輸入都放在一行中。 例如,在這段代碼中,我采用了 3 個輸入,但在 3 個不同的行中。 但我必須在單行中輸入 2 個輸入和 1 個字符。 第一個數字第二個字符,然后是第三個數字。 你能幫助我嗎?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
你可以嘗試這樣的事情:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
注意:這里沒有驗證輸入。
嘗試以下方式
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
這里numbers
和operator
由"space"
分隔。 現在,您可以通過sum array
調用它們。
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
然后,您可以像以前那樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.