使用用户输入的数字(以0结尾),然后计算它们的平方并将其存储在Java文件中
我尝试使用数组和循环来实现它,但我的第一个错误是循环本身。即使用户输入0,循环也会继续。我找不到问题所在。请帮忙
以下是代码:
import java.util.*;
import java.io.*;
public class Num2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
int[] num = new int[99];
System.out.println("Enter a number or press 0 to stop: ");
num[0] = input.nextInt();
while(num[0] != 0)
{
for(int i=1; i < num.length; i++){
System.out.println("Enter another number or press 0 to stop: ");
num[i]= input.nextInt();
do
{
System.out.println("Enter another number or press 0 to stop: ");
num[i]= input.nextInt();
}
while(num[i] != 0);
}
}
FileOutputStream fos = new FileOutputStream("Square.txt");
PrintWriter square = null;
try{
square = new PrintWriter(fos);
}
catch(Exception e)
{
System.out.print("Could not create/find file");
System.exit(0);
}
int[] output = new int[num.length];
for(int i=0; i <= num.length; i++)
{
output[i] = i*i;
}
for(int i=0; i <= num.length; i++)
{
square.print(num[i]+"\t\t"+output[i]+" ");
}
System.out.print("Done");
}
}
# 1 楼答案
你有无限循环是因为
你也应该把
i <= num.length
改成i < num.length
示例程序: