有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    amount的作用域绑定在花括号内,因此不能在外部使用

    解决方案是将其置于if块之外(注意,如果if条件失败,amount将不会被赋值):

    int amount;
    
    if(z<100){
    
        amount=sc.nextInt();
    
    }
    
    while ( amount!=100){  }
    

    或者,您可能希望while语句位于if中:

    if ( z<100 ) {
    
        int amount=sc.nextInt();
    
        while ( amount!=100 ) {
            // something
       }
    
    }
    
  2. # 2 楼答案

    你不能,它只限于if区。或者使其范围更可见,比如在if之外声明它,并在该范围内使用它

    int amount=0;
    if ( z<100 ) {
    
    amount=sc.nextInt();
    
    }
    
    while ( amount!=100 ) { // this is right.it will now find amount variable ?
        // something
    }
    

    检查here关于java中的变量作用域

  3. # 3 楼答案

    为了在外部作用域中使用amount,您需要在if块之外声明它:

    int amount;
    if (z<100){
        amount=sc.nextInt();
    }
    

    要能够读取其值,还需要确保在所有路径中为其分配值。您尚未演示如何执行此操作,但有一个选项是使用其默认值0

    int amount = 0;
    if (z<100) {
        amount = sc.nextInt();
    }
    

    或者更简洁地使用条件运算符:

    int amount = (z<100) ? sc.nextInt() : 0;