首页 > 解决方案 > 创建约会中心程序,但无法将变量保存到循环之外

问题描述

这是我到目前为止所写的:

import java.util.Scanner; 
public class appointment {
public static void main(String[]args) {
    int input;
    int appointment = 0;
    String name;
    int time;
    do { 
    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to ACEPrep Appointment Center! How can we help you? 
(1. Make an appointment 2. Check Appointment Details 3. Check Number of Appointments 4. Leave");
    input=Integer.parseInt(sc.nextLine());
    if(input==1) {
        System.out.println("Name:");
        name=sc.nextLine();
        boolean name2=true;
        if(name2==true) {
            System.out.println("Select a time between 1-8 PM:");
            time=sc.nextInt();
            System.out.println("Saved! You have an appointment at " + time +" PM with " + name);
            appointment++;
        }
    }
    if(input==2) {
        do{
        System.out.println("You have an appointment with " + name + "  at " + time); 
        }while(appointment<appointment+1);
    }
    if(input==3) {
        System.out.println("You have " + appointment + " appointment(s).");
    }
    if(input==4) {
        System.out.println("Thank you for using us! Goodbye!");
        break;
    }
    }while(input<4);
}
}

对于具有 的行System.out.println("You have an appointment with " + name + " at " + time);,它表示由于没有值而无法调用变量,并且我想将第一个循环中的变量值保存到原始变量中,但我不知道该怎么做。请问我能得到一些帮助吗?

标签: javaloops

解决方案


你必须初始化: String name = ""; int time = 0;

这也是一个无限循环do{...}while(appointment<appointment+1);


推荐阅读