簡體   English   中英

如何請求用戶選擇五個或更少的變量進行定義?

[英]How can I request the user to select five or less variables to define?

我在理解分配問題時遇到問題,特別是該問題要求我創建5個整數...但是我想實現一種方法,以使它小於等於5(如果用戶選擇)。 我怎樣才能做到這一點? 抱歉,我是Java新手。

package realestatepropvalue;

import java.util.Scanner;
public class RealEstatePropertyValue
{
public static void main(String[] args) 
{
    Scanner sc = new Scanner ( System.in );        
    System.out.println ( "Hello friend, you will enter a series "
            + "of fields that'll calculate your Real Estate Property Value.");

    System.out.print ("Please enter a Street Number ");
    String streetnum = sc.next();
    sc.nextLine();
    System.out.println ("You entered the Street Number, " +streetnum );

    System.out.print ( "Please enter a Street Name ");
    String streetnam = sc.nextLine();
    System.out.println ("You entered the Street Name, " + streetnam +   " " );

    System.out.print ("Please enter the number of rooms! (Up to 5!) ");

    int roomcount = sc.nextInt();

    String[] places = new String[5];
        for(int i = 0; i < places.length; i++) {
        places[i] = "Place Number: " + i;
        }

        sc.nextLine();

    System.out.println("You said that there were " + roomcount + " rooms!");

    System.out.print ("Please enter the types of rooms (up to " +roomcount+ ") that fill up the " + roomcount + " rooms!\n"
            + "(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!) \n ") ;

感謝您的協助!

您可以將輸入置於循環中,直到滿足要查找的要求,然后將數組的大小設置為輸入:

System.out.print ("Please enter the number of rooms! (Up to 5!) ");

while(true){
    roomCount = sc.nextInt();
    if(roomCount <= 5 && roomCount > 0){
        break;
    }else{
        System.out.println("Invalid amount of rooms");
    }
}

String[] places = new String[roomCount];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM