initialized变量表示未初始化

x3naxklr  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(416)
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner numb = new Scanner(System.in);
    int r;
    int x;
    int y;
    int z;
    int rr;
    int xx;
    int yy;
    int zz;
    boolean a1 = false;
    boolean a2 = false;
    boolean a3 = false;
    boolean a4 = false;
    System.out.println("Type four one's or zero's to convert a base 2 number to base 10. Please press enter between each one or zero: ");
    r = numb.nextInt();
    while (a1 == false) {
      if (r == 0) {
        a1 = true;
        rr = 0;
        } else if (r == 1) {
        a1 = true;
        rr = 8;
        } else {
        a1 = false;
        System.out.println("Please enter a 1 or a 0: ");
        r = numb.nextInt(); 
        } //end else
      } //end while
    x = numb.nextInt();
    while (a2 == false) {
      if (x == 0) {
        a2 = true;
        xx = 0;
        } else if (x == 1) {
        a2 = true;
        xx = 4;
        } else {
        a2 = false;
        System.out.println("Please enter a 1 or a 0: ");
        x = numb.nextInt(); 
        } //end else
      } //end while
    y = numb.nextInt();
    while (a3 == false) {
      if (y == 0) {
        a3 = true;
        yy = 0;
        } else if (y == 1) {
        a3 = true;
        yy = 2;
        } else {
        a3 = false;
        System.out.println("Please enter a 1 or a 0: ");
        y = numb.nextInt(); 
        } //end else
      } //end while
    z = numb.nextInt();
    while (a4 == false) {
      if (z == 0) {
        a4 = true;
        zz = 0;
        } else if (z == 1) {
        a4 = true;
        zz = 1;
        } else {
        a4 = false;
        System.out.println("Please enter a 1 or a 0: ");
        z = numb.nextInt();
        } //end else
      } //end while
      int a = rr + xx + yy + zz;
      System.out.println("You entered " + r + x + y + z + ", in base 10 that number is " + a);
    } //end main
} //end class Main

如果有人对如何解决这个问题有任何想法,我们将不胜感激。代码运行时出错,显示的错误消息是:“变量rr,xx,yy,zz可能尚未初始化”。我试过很多不同的方法,但都不能使代码与rr+xx+yy+zz的结果相等。刚开始学习java,所以我不太自信,我不仅仅是忽视了我做错的事情。提前谢谢!

li9yvcax

li9yvcax1#

考虑到您的代码:

int r; // You declared the variable [r] without initializing it with a valid integer value.

while (a1 == false) {
    if (r == 0) { 
    // It is semantically and syntactically wrong to compare the value of an...
    // ...undefined variable to a defined variable or a value.
        a1 = true;
        rr = 0;
    } else if (r == 1) {
        a1 = true;
        rr = 8;
    } else {
        a1 = false;

    System.out.println("Please enter a 1 or a 0: ");
    r = numb.nextInt(); 
    } //end else
  } //end while
x = numb.nextInt();

这类似于比较一个空瓶子和一个满瓶子的水量。这不是一个明智的比较,因为前者甚至不含水。我希望我的类比能有所帮助。

tcbh2hod

tcbh2hod2#

初始化变量时,将其赋值为0即可

相关问题