I want to write a program that keeps track of how many times a bus is late.
So the user is asked to enter an int value, indicating how many minutes late.
Once a negative int is entered, the program should stop.
What I’m having trouble with is making the program repeat only for inputs of 0 or more.
The program repeats regardless of what int is inputted.
I did something like below:
import java.util.Scanner;
public class LateBus {
public static void main(String[] args) {
int enter_minutes = enterMinutes();
loop(enter_minutes);
}
public static int enterMinutes() {
Scanner enter = new Scanner(System.in);
System.out.print("How many minutes late was the bus? ");
int late = enter.nextInt();
return late;
}
public static void loop(int a) {
while (a >= 0) {
enterMinutes();
}
}
}
Let's look at this function:
public static void loop(int a) {
while (a >= 0) {
enterMinutes();
}
}
The value of a never changes. a >= 0 will always be true or never be true depending on the initial value for a. Since a is used internally to this function, you should not pass it in as a parameter. And you should be sure to change it:
public static void loop() {
int a = enterMinutes();
while (a >= 0) {
a = enterMinutes();
}
}
Now you call the function like this:
public static void main(String[] args) {
loop();
}
Note:
Everyone makes logic mistakes in their code as they write it. To find them, you need to learn how to debug. I suggest that you read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for some tips on how to debug your code so that you can find these kinds of problems on your own.
The while loop will stop when a is negative, but you do not change its value.
Do it like this
while (a >= 0) {
a = enterMinutes();
}
now the value changes to what the user inputs.
Related
Today, I have taken an exam, and there was a question:
Write a method which prints integer numbers in the ascending order recursively from 1 to n:
public class PrintIntegersAscendingOrder {
static int counter = 0;
public static void PrintIntegersAscendingOrder (int n)
{
if (n == 1)
{
System.out.printf("%d\n", ++counter);
}
else
{
System.out.printf("%d ", ++counter);
PrintIntegersAscendingOrder(n-1);
}
}
public static void main (String args[])
{
PrintIntegersAscendingOrder(5);
}
}
Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?
You can do it like this:
public class IntegerAscendingOrder {
public static void main(String[] args) throws Exception {
printIntegersAscendingOrder(n);
}
private static void printIntegersAscendingOrder(int i) {
if (i < 1) {
return;
}
printIntegersAscendingOrder(i-1);
System.out.println(i);
}
}
You don't need the counter variable in the class, using recursion you can limit the method call within the method itself.
Notice the if (i < 1) {return;} line, this will terminate the recursive method call(s).
This article should help you Getting started with recursion
Do it as follows:
public class Main {
public static void printIntegersAscendingOrder(int n) {
if (n == 0) {
return;
}
printIntegersAscendingOrder(n - 1);
System.out.printf("%d ", n);
}
public static void main(String args[]) {
printIntegersAscendingOrder(5);
}
}
Output:
1 2 3 4 5
As #RobOhRob has already pointed out, the counter defeats the purpose of recursion in your code. When you are calling a function recursively, you need to analyse three important things:
When to stop the recursive call
Processing before making the recursive call
Processing before making the recursive call
Since you are already decreasing the parameter by 1 and passing it to the method to call it recursively, you can simply make use of this parameter instead of creating an additional variable (e.g. counter).
In your code you have defined in your class a method PrintIntegersAscendingOrder having the same name of the class PrintIntegersAscendingOrder containing it. This is an error that can be avoided for example renaming the including class to PrintIntegers. Below the code of class without the error and with the recursive method:
public class PrintIntegers {
public static void PrintIntegersAscendingOrder(int n) {
if (n > 0) {
PrintIntegersAscendingOrder(n - 1);
System.out.printf("%d\n", n);
}
}
public static void main (String args[]) {
PrintIntegersAscendingOrder(5);
}
}
I want to implement this program but it throws errors on every function call and runs an infinite loop.
class abc
{
public static void main(String[] args) {
int n=16;
calll(n);
}
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
n=n+5;
calll(n);
return n;
}
}
}
There is no end condition to your function.
Whether n is greater than 5 or not you run the calll function, which then runs the calll function again to infinite.
You need a conditon that will end the recursion, for instance changing the call function to this:
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
return n;
}
}
However the function is still rather pointless as you don't actually do anything with n. Keep in mind that the n that you define in the main function is never modified.
Usually, when I want a chance of something happening I use a random number, then an if statement to check for a specific outcome, like so:
public static void main(String[] args){
public boolean chance(){
Random r = new Random();
int chance = Random(100)+1; //For a 1/100 chance
if(chance == 1){
return true;
}else{
return false;
}
}
}
Are there more efficient ways to do this in java, like a java library method, or am I stuck with creating it every time I want to use a percent chance.
Assuming x represents a percent chance:
public static boolean chance(int x) {
return ThreadLocalRandom.current().nextInt(100) < x;
}
how about:
import java.util.Random;
class Oink {
private Random rnd;
Boolean chance() {
return (rnd.nextDouble()<0.01);
}
}
So I have a super class called Factorial and two subclasses called Fibonacci and Arithmetic. In my main super class which I call the method using a polymorphic array from my main class, I have an input box inquiry that I want to only show up once, but instead it shows up multiple times. Is there anyway I can stop this? My main class is called PolyMorphism. I know it's tedious but it's the way I made the program and want it to be :p
public class Polymorphism {
public static void main(String[] args) {
Factorial arrayObject[] = new Factorial[3];
arrayObject[0] = new Factorial();
arrayObject[1] = new Fibonacci();
arrayObject[2] = new Arithmetic();
for(int x=0;x<arrayObject.length;++x){
arrayObject[x].sequence();
}
public class Factorial extends JFrame {
//this input box shows up 3 times when I launch.
public final String valueInput = JOptionPane.showInputDialog("Please enter a number between 1 and 20.");
public void sequence(){
System.out.println("Factorial:");
System.out.println(fact(Integer.valueOf(valueInput)));
public static long fact (int n){
if (n <= 1){
return 1;
}else
return n * fact(n-1);
}
public class Fibonacci extends Factorial {
public void sequence(){
int inputValue = Integer.parseInt(valueInput);
System.out.println("Fibonacci Sequence");
/**for (int value = 0; value < inputValue; value++){
System.out.println(fibonacciSequence(value));
} **/
System.out.println(fibonacciSequence(inputValue));
}
public static long fibonacciSequence(int v) {
// TODO Auto-generated method stub
if(v == 0) {
return 0;
}else if (v <= 2){
return 1;
}
long fibonacci = fibonacciSequence(v - 1) + fibonacciSequence(v-2);
return fibonacci;
}
}
The comment with the problem is under the Factorial class, and disregard the JFrame for now.
In your Factorial class, you have this:
public final String valueInput = JOptionPane.showInputDialog("Please enter a number between 1 and 20.");
Which means every time you create an instance of it or a subclass, that input dialog will pop up.
The answer is: Don't do that.
Put it in a method and call the method when you want the input dialog to show.
Each Factorial instance (of which you have three) has its own valueInput property, so the behavior is as expected. You could make this field static (and therefore shared), but it's still not clear what you're trying to accomplish.
It's most likely the case that you should be separating the input display from the Factorial implementation entirely.
i am a basic programing student and i need help on how to make a particular program.
The scenario is: people go in and out of an event and i need to keep track of them. the limit of people allowed is 100. People can come alone or en masse. As people go in and out the total should change. people should be denied access after limit is reached.
everything will be going into JOptionPane.
not sure if im looking at the best site for help but, any advice would help.
i know i will make a while loop for this.
import javax.swing.JOptionPane;
public class HwTwoPt2 {
public static void main(String[] args) {
int enter, exit, total;
int maxCapacity = 106;
int count = 0;
int groupAmt = 0;
while(count != maxCapacity){
groupAmt = Integer.parseInt(JOptionPane.showInputDialog("Enter total amount in the group: "));
}
}
}
If you're wanting to deny people access once a limit has been hit you'll want to change your while loop to something like:
while(count < maxCapacity)
If you go with != maxCapacity, a value of 107 would pass and allow people entry.
You will also want to verify groupAmt before adding it to maxCapacity.
if((count + groupAmt) < maxCapacity)
{
count += groupAmt;
}
I'd advise you to encapsulate all this into an object. Java's an object-oriented language. Better to get used to thinking in terms of encapsulation and information hiding early.
Something like this:
public class CapacityTracker {
private static final int DEFAULT_MAX_CAPACITY = 100;
private int currentCapacity;
private int maxCapacity;
public CapacityTracker() {
this(DEFAULT_MAX_CAPACITY);
}
public CapacityTracker(int maxCapacity) {
this.maxCapacity = ((maxCapacity <= 0) ? DEFAULT_MAX_CAPACITY : maxCapacity);
this.currentCapacity = 0;
}
public int getCurrentCapacity() { return this.currentCapacity; }
public void addAttendees(int x) {
if (x > 0) {
if ((this.currentCapacity+x) > this.maxCapacity) {
throw new IllegalArgumentException("max capacity exceeded");
} else {
this.currentCapacity += x;
}
}
}
}
I'd keep adding methods to make this more convenient for me to use.
I might create a custom CapacityExceededException as well.