有 Java 编程相关的问题?

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

使用用户输入的数字(以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) 个答案

  1. # 1 楼答案

    你有无限循环是因为

    while(num[0] != 0)//If first number enters is not 0 then infinite loop.
    

    你也应该把i <= num.length改成i < num.length

    示例程序:

    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(System.in);
        int[] num = new int[5];//Changed to 5 for testing
    
        for(int i=0; i < num.length; i++){//Getting 5 Numbers
                System.out.println("Enter another number or press 0 to stop: ");
                int n= input.nextInt();
                if(n%10 == 0)
                {
                   num[i] = n/10;
                   break;//Breaks on user gave input ends with 0
                }
                num[i] = n;
        }
    
        int[] output = new int[num.length];
    
        for(int i=0; i < num.length; i++)
        {
            output[i] = num[i]*num[i];//Calculating Square of entered numbers
        }
    
        for(int i=0; i < num.length; i++)
        {
            System.out.println(num[i]+"\t\t"+output[i]+" "); //printing instead of writing in file
    
        }
    
        System.out.print("Done");
    }