[英]How can I read any user input from the scanner library?
I'm fairly new to java, so don't think this is some idiot. 我对Java很陌生,所以不要认为这是个白痴。 Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add.
无论如何,我一直在尝试制作一个可以从控制台读取特定字母的程序,然后确定要使用的操作,比如说要添加。 However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
但是,我无法通过If循环来读取决定使用哪个运算符的变量,下面是代码,请提供帮助。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit). (我将说明简化了,以使其适合)。
This is just an example to get you started in the right direction. 这只是一个示例,可以帮助您正确地开始工作。
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. 如果在扫描仪上使用hasNext(),它将等待输入,直到停止程序为止。 Also using equals() is a better way of comparing strings.
另外,使用equals()是比较字符串的更好方法。
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.