1. 使用java if语句做怎么做
利用Boolean类提供的方法parseBoolean可以实现在if语句中使用String。
具体分析如下:if(expression)中,expression必须是逻辑变量、逻辑表达式或者返回值为逻辑类型的方法。那么想在java语言中的if语句中使用String类型,就需要将String类型转换成Boolean(或者boolean)类型。
刚好Boolean类提供了将String类型转换成boolean类型的方法parseBoolean。api文档是这样写的:public static boolean parseBoolean(String s) 将字符串参数解析为boolean值。
如果String参数不是null且在忽略大小写时等于"true",则返回的boolean表示true值。示例:Boolean.parseBoolean("True") 返回 true。
示例:Boolean.parseBoolean("yes") 返回 false。所以利用if(Boolean.parseBoolean(String variable))就可以实现在if语句中使用String。
2. java if语句嵌套if语句
import java.util.Scanner;
public class jsq {
//我想写一个计算器,if这样嵌套报错,在c里就可以。我刚学Java,该怎么改?
public static void main(String[] args)
{Scanner s=new Scanner(System.in);
Scanner sz=new Scanner(System.in);
Scanner o=new Scanner(System.in);
int q,w,e = 0;
char p;
System.out.println("请输入两个数字后输入运算符号");
q=s.nextInt();
w=sz.nextInt();
String p1=o.next();
if (p1.equals("+")){
e=q+w;
System.out.println("结果是:"+e);
}
else if(p1.equals("-")){
e=q-w;
System.out.println("结果是:"+e);
}
else if(p1.equals("/")){
e=q/w;
System.out.println("结果是:"+e);
}
else if(p1.equals("*")){
e=q*w;
System.out.println("结果是:"+e);
}
{
}
}
}
//从控制台读入 不能读取char类型的字符可以用String类型 在用equals()函数来比较两个字符
//串的是否相等
3. Java If语句
看我写的注解部位,多了两个分号,现在程序可正常运行。
package test1;import java.util.*;public class A3T1 { public static void main(String[] args) { String Package; double hours; double purchase; //Create a Scanner object to read input Scanner keyboard=new Scanner(System.in); //Get the package which customers choice System.out.print("Choice Package:"); Package = keyboard.nextLine(); //Get the hours that customers use System.out.print("Enter hours of use:"); hours=keyboard.nextDouble(); //If customers choice PackageA, they should pay how much according to the hours of use if(Package.equalsIgnoreCase("A")) { if(hours<=10) {purchase = 9.95;} else {purchase = 9.95 + 2*( hours - 10);} System.out.println("$"+purchase); } //If customers choice PackageB, they should pay how much according to the hours of use else if(Package.equalsIgnoreCase("B"))//这个位置你多了一个“;” { if(hours<=20) {purchase = 13.95;} else {purchase = 13.95+(hours-20)*1;} System.out.println("$"+purchase); } //If customers choice PackageC, they should pay how much according to the hours of use else if (Package.equalsIgnoreCase("C"))//这个位置你也多了一个“;” { purchase = 19.95; System.out.println("$"+purchase);}//it the users enters the other package letter except for A,B ,or C else System.out.println( "Invalid Package.Please Enter A, B,or C.");}}。
转载请注明出处育才学习网 » javaif语句怎么写