So I had to make a program that calculates the volume of sound at a different distance, given a reference difference, and sound level, and the new distance. It works sometimes but depends on what values I put in.
Much of the time it tells me the new volume level is the same as the initial (whatever i set it as) but then other times it works. It must be a problem with the actual mathematical equation but I cant seem to spot an error.
package lab8;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class GUISoundLevels extends JFrame implements ActionListener {
private JLabel inputSoundLevelLabel;
private JTextField inputSoundLevelText;
private JLabel distance1Label;
private JTextField distance1Text;
private JLabel distance2Label;
private JTextField distance2Text;
private JButton go;
private JTextField outputSoundLevel;
public GUISoundLevels() {
super("Sound Levels: GUI");
setSize(575,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container myPane = getContentPane();
myPane.setLayout(new FlowLayout());
inputSoundLevelLabel = new JLabel("Enter reference sound level (in decibels)");
inputSoundLevelText = new JTextField(20);
distance1Label = new JLabel("Enter the reference distance (in meters)");
distance1Text = new JTextField(20);
distance2Label = new JLabel("Enter the new distance (in meters)");
distance2Text = new JTextField(20);
go = new JButton("go");
outputSoundLevel = new JTextField("output will appear here", 30);
add(inputSoundLevelLabel);
add(inputSoundLevelText);
add(distance1Label);
add(distance1Text);
add(distance2Label);
add(distance2Text);
add(go);
go.addActionListener(this);
add(outputSoundLevel);
setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
int inSoundLevel = new Integer(inputSoundLevelText.getText());
int refDistance = new Integer(distance1Text.getText());
int newDistance = new Integer(distance2Text.getText());
int finalSoundLevel = new Integer((int) ((inSoundLevel -Math.round( 20 * Math.log10(newDistance/refDistance) ) )));
outputSoundLevel.setText("The SPL of the sound at distance " + Integer.toString(newDistance) + " is " + Integer.toString(finalSoundLevel) + " dB");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new GUISoundLevels();
}
}