在switch / case语句中循环

时间:2017-10-16 08:48:24

标签: java loops switch-statement case

我一直在玩基本的Java,并开始创建一个项目,其中包括用户输入,系统输出和开关/案例陈述。用户输入给定的动物,系统输出与动物有关的必要噪音。目前程序会询问用户一次然后结束,但我希望用户能够输入他们喜欢的动物并获得适当的响应。欢迎任何帮助,谢谢。 (我知道我的代码中可能存在一些错误,但我只是刚刚开始使用Java。)

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String myString;
System.out.println("Enter your first animal: ");
myString = user_input.next();

loop: switch (myString) {

case "Cow":
    System.out.println("Mooo!");
    break;

case "Sheep":
    System.out.println("Baaaa!");
    break;

case "Mouse":
    System.out.println("Squeak Squeak!");
    break;

case "Horse":
    System.out.println("Neighhh!");
    break;

case "Goat":
    System.out.println("Skreachh!");
    break;

case "Fish":
    System.out.println("*Bubble Bubble*");
    break;

default:
    System.out.println("Invalid animal.");
    break;

    }
}

2 个答案:

答案 0 :(得分:3)

你需要一个循环和一个条件来停止。

//Data.js
import React,{ Component } from 'react'
import { connect } from 'react-redux';
import raws from './another.json';

import Chart from './Chart'; //fix the path to Chart.js if that file is not in same folder.

function filter_pie(apple,lemon){
   //...put raws and redux together to filter some array we need
  }
  return [newArray,pieName]
}

class Data extends Component {
  render () {
    const { props: { apple, lemon } } = this
    let data_pie = filter_pie( apple, lemon )
    return(
      <div>
        { //data_pie}
        { //instead use <Chart /> here and pass data_pie as prop }
        <Chart data={data_pie} />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    apple:state.apple,
    lemon:state.lemon,

  };
}

export default connect(mapStateToProps)(Data);

答案 1 :(得分:0)

您也可以使用do-while循环

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        do {
            System.out.println("Enter your first animal: ");
            myString = input.next();
            switch (myString) {
                case "Cow":
                    System.out.println("Mooo!");
                    break;
                         ........
                default:
                    System.out.println("Invalid animal.");
                    break;
            }
        } while (!myString.equals("Stop"));
    }

您可以从herehere

获得详细说明