【问题标题】:How can I define a char variable within a method?如何在方法中定义 char 变量?
【发布时间】:2021-10-28 20:12:07
【问题描述】:

我正在尝试编写一个循环,当用户输入 Y 时,循环继续,当用户输入 N 时,循环停止。但是,当我尝试分配变量时,我收到错误“无法从 void 转换为 char”,我显然在某处搞砸了,但我不确定在哪里。

import java.util.Scanner;

public class SimpleList {

    public static void main(String[] args) {
    
        System.out.println("Welcome to the Simple List Class");
        
        getData();  
        
    }
    private static void getData() {
        
        Scanner input = new Scanner(System.in);
        float[] numbers = new float[10];
        
        System.out.println("Enter a non-negative floating point value: ");
        
        for(int i = 0; i < 10; i++) {
            float x = input.nextFloat();
            if (x > 0) {
                numbers[i] = x;
                char ans = System.out.print("Would you like to input another value? (Y or N)? ");
            }
            else {
                System.out.println("That is not a valid. Try Again.");
            }
        
        }
        
        System.out.println(Arrays.toString(numbers));
        
        }
        
    } ```

【问题讨论】:

  • System.out.print 不返回任何内容。您需要使用您的Scanner 来获得答案。

标签: java variables char


【解决方案1】:

您将 ans 分配给 System.out.print() 的结果,这是一个 void 方法。

相反,请事先创建提示并使用Scanner 获取输入:

public class SimpleList {

    public static void main(String[] args) {
    
        System.out.println("Welcome to the Simple List Class");
        
        getData();  
        
    }

    private static void getData() {
        
        Scanner input = new Scanner(System.in);
        float[] numbers = new float[10];
        
        System.out.println("Enter a non-negative floating point value: ");
        
        for(int i = 0; i < 10; i++) {
            float x = input.nextFloat();
            if (x > 0) {
                numbers[i] = x;

                // New Prompt
                System.out.print("Would you like to input another value? (Y or N)? ");
                // Take input and set ans
                char ans = input.next().charAt(0);
            }
            else {
                System.out.println("That is not a valid. Try Again.");
            }
        
        }
        
        System.out.println(Arrays.toString(numbers));
        
    }
        
}

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多