【问题标题】:How to quit scanner when input is negative?输入为负时如何退出扫描仪?
【发布时间】:2019-06-21 07:42:39
【问题描述】:

这是说明。

编写一个程序,读取一系列输入值并使用星号显示值的条形图。您可以假设所有值都是正数。首先找出最大值。那是价值的酒吧应该用 40 个星号绘制。较短的条形应按比例使用较少的星号。

这是我到目前为止提出的。一切都很好,只是我需要输入一个字母而不是负数来退出扫描。我已经尝试过(if(

import java.util.Scanner;

public class BarChart1 {
    public static void main(String [] args) {
        int[] arr = new int[100];
        int currentSize = 0;
        System.out.println("Enter a sequence of positive integers.  "

                + ("Enter a negative value to quit:"));
        Scanner in = new Scanner(System.in);

        while(in.hasNextInt()) {
        int num = in.nextInt();
            if (num < 0) {
                break;
            }
            else {
                arr[currentSize] = in.nextInt();
                currentSize++;
            }
        }

        //will find the max
        double max = arr[0];
        int y = 0;
        for (int i = 1; i < arr.length; i++) {
            y = i + 1;
            if(max < arr[i]) {
                max = arr[i];
                //y = i + 1;
            }

        }

        System.out.println("Max number is: " + max);
        System.out.println("Number of digits = " + y);
        System.out.println(Math.abs(-1));

        double scale = 40/max;
        System.out.println("Scale = " + scale);


        for (int i = 0; i < y; i++) {
            double h = scale * arr[i];
            if (h != 0) {
                for (int j = 1; j <= h; j ++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }

}

这是结果。

1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************

我只需要星号。正在打印的所有其他内容仅用于检查目的。

【问题讨论】:

  • 您的代码未显示您描述的任何尝试。为什么读取整数并检查&lt; 0 不起作用? (您知道break 关键字吗? - 如果不查找。)如果是负整数,您希望发生什么?退出应用程序还是只接受输入?
  • 是的。我的代码没有描述我所描述的任何尝试,因为上面的代码至少是有效的。
  • 您是否尝试读取整数并在将其添加到数组或中断循环之前对其进行检查?你能告诉我们你是如何尝试的吗?
  • 诚实地使用一个字母(或其他非整数)来中断循环对我来说似乎不是一个坏主意(引用你的问题)“你可以假设所有的价值观都是积极的。 "
  • @Aaron 这不是一个坏主意,但指令特别指出负数使它退出而不是字母。

标签: java input user-input


【解决方案1】:

你可以试试这个:

    while(in.hasNextInt()) {
     int num =in.nextInt();
          if(num <0){
              break;
             }
          else{
               arr[currentSize] = num;
               currentSize++;
            }
}

【讨论】:

  • 这正是我的意思,但我希望 OP 会先向我们展示他的尝试,以便我们可以帮助他更好地理解他的方式的错误;)
  • 我猜它阻止了扫描仪接受负整数但打印仍然损坏,为什么?
  • @CateDoge 你能把错误的输出发给我吗..(不要气馁..你已经接近解决方案了)
  • @NamrataShukla 在我们讲话时,我的编程课不及格。看来同学们比我更懂。我为自己的不理解感到羞耻。我觉得格格不入。 T.T
猜你喜欢
  • 2016-06-20
  • 2019-11-08
  • 2017-09-04
  • 1970-01-01
  • 2017-09-23
  • 2015-03-22
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
相关资源
最近更新 更多