0

The assignment is to write a Java program that takes in user input for a budget, then takes in expenses, and once the user finishes inputting all the expenses, tells you whether you went over or under budget. The assignment states that you are not allowed to alter the given code:

import java.util.Scanner;
class Main {
  public static void main(String[] args) 
  {
    Scanner in = new Scanner(System.in);
    String keep_going = "yes";
    while(keep_going.equalsIgnoreCase("yes"))
      {
        //put your code here       
        //Get the amount needed        
        //do not alter the given code here
        System.out.print("Do you want to run the program again? ");
        System.out.println("Enter yes or no:");
        keep_going = in.nextLine();
      }
    System.out.println("The program has terminated!");
    
}
}

This is the code that I wrote:


import java.util.Scanner;
class Main {
  public static void main(String[] args) 
  {
    Scanner in = new Scanner(System.in);
    String keep_going = "yes";
    double amount = 0;
    double temp = 0;
    double budget = 0;

    System.out.println("What is your budget?");
    budget = in.nextInt();
    while(keep_going.equalsIgnoreCase("yes"))
      {
        //put your code here
        
       
        //Get the amount needed
          System.out.println("What is the expense amount?");
        temp = in.nextDouble();
        amount = temp + amount;
          
        //do not alter the given code here
        System.out.print("Do you want to run the program again?\n ");
        System.out.print("Enter yes or no:\n ");
        keep_going = in.nextLine();
      }
    System.out.println("The program has terminated!");
    if (amount <= budget) {
      System.out.println("You are under budget!");
    }
    else {
      System.out.println("You are over budget :( ");
  }
}
}

When I run it, it automatically leaves the while loop and doesn't let me input "yes" or "no". What do I do?

Zaynab B.
  • 9
  • 2
  • Don't mix `nextLine` and `nextX`. If you can't edit the code that's already there (which should be using `scanner.useDelimiter("\\R")`, or, at least, just `.next()` instead of `.nextLine()`, then I guess you can't use .nextInt and will have to use `Integer.parseInt(scanner.nextLine())` instead. – rzwitserloot Apr 18 '23 at 22:22
  • On a side: Don't you think the `if (amount <= budget) {` IF/ELSE block should be directly under the `amount = temp + amount;` code line? If you want to continue using your existing code...consume the Enter key hit directly after the `temp = in.nextDouble();` code line by adding: `in.nectLine();`. – DevilsHnd - 退職した Apr 18 '23 at 22:34
  • I mean `in.nextLine();` On another side. You don't need to add `\n` to your output if you use `System.out.println()` instead of `System.out.print()`. – DevilsHnd - 退職した Apr 18 '23 at 22:41

0 Answers0