简体   繁体   English

我正在尝试打印程序,但是运行该程序时什么也没发生

[英]I'm trying to get my program to print, but nothing happens when I run it

This code takes two numbers a base, and an integer, and it multiplies it out, but when I try and run it, it takes the numbers, then nothing happens. 这段代码将两个数字作为底数,然后将其与一个整数相乘,但是当我尝试运行它时,它接受了数字,然后什么也没有发生。

import java.util.Scanner;
public class RaisedToThePower 
{ 
public static void main(String [] args)

 {

 Scanner reader = new Scanner(System.in);

 int base;
 int exponent;
 double x;

 System.out.println("Enter the base");
 base = reader.nextInt();

 System.out.println("Enter the exponent");
 exponent = reader.nextInt();

 x = base^exponent;

 while (exponent > (-1));
{
   System.out.println(x);
  }

 while (exponent <= -1);
  {
    System.out.println("Thanks for playing");
  }
 }
}

Why nothing prints: 为什么什么都不打印:

You are not printing anything, since you do 您没有打印任何东西,因为

while (exponent > (-1)) ;

The ; ; ends the while statement and since it is an infinite loop you never print anything. 结束while语句,由于它是一个无限循环,因此您从不打印任何内容。

{
    System.out.println(x);
}

This is just a statement in a block, which does not belong to the while 这只是一个语句块,不属于while

To fix this: 要解决此问题:

while (exponent > (-1)) // no ; here
{
    System.out.println(x);
}

This will still be an endless loop, if the exponent is bigger than -1. 如果指数大于-1,这仍将是一个无限循环。

The next while has the same problem. 下一阵子有同样的问题。


Additional problem: 附加问题:

 x = base^exponent;

This does not execute an exponentiation. 这不会执行幂运算。

^ is the XOR operator in java. ^是Java中的XOR运算符。 (See Java Operators ) (请参阅Java运算符

To get the power of an exponent you need to use: 要获得指数的幂,您需要使用:

Math.pow(base, exponent);

From the java docs: 从Java文档:

Returns the value of the first argument raised to the power of the second argument. 返回提高到第二个参数的幂的第一个参数的值。

You have ; 你有 ; at end of each while loop while (exponent > (-1)); 在每个while循环结束时while(指数>(-1)); And you are not doing anything inside the both loop except printing. 而且除了打印之外,您都没有在两个循环内执行任何操作。 Any of the loop get hit it will be infinite loop. 任何循环被命中都会是无限循环。

That is not how you get power of a base: 那不是您获得基础力量的方式:

x = base ^ exponential;

A simple Math.pow example, display 2 to the power of 8. 一个简单的Math.pow示例,显示2到8的幂。

Math.pow(2, 8)

For details 详情

First answer already explains everything. 第一个答案已经说明了一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM