简体   繁体   中英

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

I'm having trouble understanding an assignment problem, specifically the problem asks me to create five integers... but I'd like to implement a way to make it 5 or less, if the user chooses. How can I do this? I apologize, I'm new to 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 ") ;

Thank you for any assistance!

You could put the input in a loop until you meet the requirements you are looking for and then set the size of your array to the input:

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM