Anonymous user
99 bottles of beer: Difference between revisions
→{{header|Java}}: consistent formatting, cleanup
(→{{header|Java}}: consistent formatting, cleanup) |
|||
Line 3,819:
MessageFormat's choice operator is used to properly format plurals.
<lang java>import java.text.MessageFormat;
public class Beer {
return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n);
}
String bottles = bottles(99);
for (int n = 99; n > 0; ) {
System.out.println(bottles + " on the wall");
System.out.println(bottles);
System.out.println(
bottles = bottles(--n);
System.out.println(
System.out.println();
}
}
}</lang>
'''Optimized for speed and few I/O operations'''
<lang java>public class Beer {
public static void main(String[] args) {
int bottles = 99;
StringBuilder sb = new StringBuilder();
String verse1 = " bottles of beer on the wall\n";
String verse2 = " bottles of beer.\nTake one down, pass it around,\n";
while (
sb.append(
System.out.println(sb.append(
}
}</lang>
'''Recursive'''
<lang java>public class Beer {
public static void main(String args[]) {
song(99);
}
public static void song(int bottles) {
if (bottles >= 0) {
if (bottles > 1)
System.out.println(bottles + " bottles of beer on the wall\n" + bottles + " bottles of beer\nTake one down, pass it around\n" + (bottles - 1) + " bottles of beer on the wall.\n");
else if (bottles == 1)
System.out.println(bottles + " bottle of beer on the wall\n" + bottles + " bottle of beer\nTake one down, pass it around\n" + (bottles - 1) + " bottles of beer on the wall.\n");
else
song(bottles - 1);
}
}
}</lang>
Line 3,891 ⟶ 3,884:
<lang java>import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Beer extends JFrame {
private
private JTextArea text;
public static void main(String[] args) {
new Beer().setVisible(true);
}
public Beer() {
x = 99;
JButton take = new JButton("Take one down, pass it around");
take.addActionListener(this::onTakeClick);
text = new JTextArea(4, 30);
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");
text.setEditable(false);
setLayout(new BorderLayout());
add(text, BorderLayout.CENTER);
add(take, BorderLayout.PAGE_END);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");
text.setText(x + " bottles of beer on the wall\n" +
if (x == 0) {
}
}
}</lang>
|