Java - Returning integer values from switch statements - switch-statement

public class CS1702_Lab8
{
public static void DaysInAMonth()
{
int daysinmonth = 0;
int days = Month(daysinmonth);
System.out.println(days);
}
public static int Month(int daysinmonth)
{
String month = "September";
switch(month)
{
case "January":
daysinmonth = 31;
break;
case "February":
daysinmonth = 28;
break;
case "March":
daysinmonth = 31;
break;
case "April":
daysinmonth = 30;
break;
case "May":
daysinmonth = 31;
break;
case "June":
daysinmonth = 30;
break;
case "July":
daysinmonth = 31;
break;
case "August":
daysinmonth = 31;
break;
case "September":
daysinmonth = 30;
break;
case "October":
daysinmonth = 31;
break;
case "November":
daysinmonth = 30;
break;
case "December":
daysinmonth = 31;
break;
default:
daysinmonth = -1;
break;
}
return daysinmonth;
}
}
Can someone tell me why nothing is printing please? I am using a switch statement in my month method and want to return the daysinmonth integer values to public static void DaysInAMonth. Im a beginner at Java so I apologise in advance for any basic errors.

Simple use static void main(String[] args) instead of DaysInAMonth().
So the whole change would only be:
public static void DaysInAMonth()
{
int daysinmonth = 0;
int days = Month(daysinmonth);
System.out.println(days);
}
to
public static void main(String[] args)
{
int daysinmonth = 0;
int days = Month(daysinmonth);
System.out.println(days);
}
Why?
Simply because every program needs a starting point. Without any main method in your class the program won't even be started.

Related

I have written code to find whether given string is anagram. for some permutations code is working fine but in some case it's failing. Any suggestion?

The above logic is working for some inputs but it get's fails while we apply some complex permutations of string. Please could anyone suggest any improvement in code and logic.
public class StringAnagram {
public static void main(String[] args) {
String s = "he_llo";
String s1 = "elloh";
boolean flag = false;
if (s.length() == s1.length()) {
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(i) == s1.charAt(j)) {
flag = true;
i++;
if(i==s.length())
break;
} else
flag = false;
}
}
} else
System.out.println("String length not match");
if(flag==true)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}

j2me, generate random location of food for simple snake game

here is my code for the snake game, the thing i need to do is generate location for the snake food, once the snake touch the snake food, it will regenerate the location of the food~pls, i really need your guys help!!! just kindly have a look
package snake;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class SnakeCanvas extends Canvas{
private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
private final Midlet midlet;
private int score = 0;
Timer t;
public SnakeCanvas(Midlet midlet)
{
this.midlet = midlet;
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
public void paint(Graphics g) {
boolean touch=false;
//drawing Background
g.setColor(0x000000);
g.fillRect(0, 0, getWidth(), getHeight());
//drawing snake
g.setColor(0xffffff);
g.fillRoundRect(currentX, currentY, 20, 20, 5, 5);
//snake food
g.setColor(234,41,42);
g.fillRect(randomX,randomY,10,10);
if((currentX-9<=randomX+4&&currentX+9>=randomX-4)&&(currentY-9<=randomY+4&&currentY+9>=randomY-4)){
addScore();
}
//drawing block
g.setColor(82,133,190);
g.fillRect(0, 0, getWidth(), 5);
g.fillRect(0, getHeight()-5, getWidth(), 5);
g.fillRect(0, 0, 5, getHeight());
g.fillRect(getWidth()-5, 0, 5, getHeight());
if((currentX>=getWidth()-10)||(currentX<5)||(currentY>=getHeight()-5)||(currentY<5))
midlet.GameOver();
g.setColor(142,255,17);
g.drawString("Score : "+score, 8, 7, Graphics.TOP|Graphics.LEFT);
repaint();
}
protected void keyPressed(int keyCode) {
System.out.println(keyCode);
switch(keyCode)
{
case -1:
condition = false;
position = false;
break;
case -2:
condition = false;
position = true;
break;
case -3:
condition = true;
position = false;
break;
case -4:
condition = true;
position= true;
break;
}
repaint();
}
private void addScore() {
score=score+1;**strong text**
}
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
}
Okay. I don't know if you managed to solve your problem but there seems to be a couple things wrong with your code.
First in this code block in the beginning:
Private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
^I am sure this does not compile, you can't have function calls when declaring header variables.
Second
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
Your block coding style is horrible and hard to read. http://en.wikipedia.org/wiki/Programming_style#Indentation has a good guide on mastering this, read it!
This applies to your switch/case statements too!
Lastly your question:
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
^ Just generates random numbers, but doesn't do anything with them. I am guessing you meant:
private void food(){
Random rand = new Random();
randomX=rand.nextInt(150) + 20;
randomY=rand.nextInt(250) + 20;
}
which sets the classes global randomX and randomY to new values.
This doesn't help though since you don't actually call the Food() function anywhere in this class! And considering it is "Private" and can only be used by this class that must be an error.
tl;dr You need to study programming some more, but it is a good effort. I will help you more in the comments if you like. If my answer helped, please accept it.
Fenix

Why is if-else for String faster than switch-case for enum?

As Java 6 does not have switch-case for String, I often change an if-else block to switch-case using enum as in the code below. However, when I tried to check the performance of the two alternatives, I found that switch-case to be slower than the if-else alternative, contrary to what I had expected. Here are some of the results that I got for the code below
Iterations If-Else Switch-Case
1 11810 1609181
10 8214 1059115
100 24141 1152494
1000 183975 1580605
10000 4452698 8710648
100000 7069243 19457585
package conditionals;
import java.util.Random;
public class StringConditionalCheck {
private static int ifElseCounter = 0;
private static int switchCaseCounter = 0;
private static final String first = "First";
private static final String second = "Second";
private static final String third = "Third";
private static final String fourth = "Fourth";
enum StringOptions {
First, Second, Third, Fourth
}
public static void main(String[] args) {
final int iterations = Integer.parseInt(args[0]);
String[] userInputs = generateUserInputs(iterations);
// Using if-else
long ifelseStartTime = System.nanoTime();
for(int i=0; i<iterations; i++){
useIfElse(userInputs[i]);
}
long ifelseEndTime = System.nanoTime();
long ifElseDuration = ifelseEndTime - ifelseStartTime;
long switchcaseStartTime = System.nanoTime();
for(int i=0; i<iterations; i++){
useSwitchCase(userInputs[i]);
}
long switchcaseEndTime = System.nanoTime();
//just to verify that both options had the same result.
long switchcaseDuration = switchcaseEndTime - switchcaseStartTime;
System.out.println(iterations + " " + ifElseDuration + " " + switchcaseDuration + " " + ifElseCounter + " " + switchCaseCounter);
}
private static String[] generateUserInputs(int numberOfInputs) {
String[] generatedInputs = new String[numberOfInputs];
String[] inputsToChooseFrom = new String[]{first, second, third, fourth};
Random r = new Random();
for (int i = 0; i < numberOfInputs; i++) {
int choice = r.nextInt(4);
generatedInputs[i] = inputsToChooseFrom[choice];
}
return generatedInputs;
}
public static void useSwitchCase(String input) {
StringOptions option = StringOptions.valueOf(input);
switch(option){
case First:
switchCaseCounter += 1;
break;
case Second:
switchCaseCounter += 2;
break;
case Third:
switchCaseCounter += 3;
break;
case Fourth:
switchCaseCounter += 4;
break;
}
}
public static void useIfElse(String input) {
if(input.equals("First")){
ifElseCounter += 1;
}else if(input.equals("Second")){
ifElseCounter += 2;
}else if(input.equals("Third")){
ifElseCounter += 3;
}else if(input.equals("Fourth")){
ifElseCounter += 4;
}
}
}
What is the cause for this difference? I was expecting that if-else would be slower as there will be more comparisons on average.
Because 99% of your time is being spent in StringOptions option = StringOptions.valueOf(input);, not in the switch
Based on the source code, the StringOptions.valueOf call does several complicated things, including building a HashMap every call, whereas String.equals simply loops through the string once.
Compare the source code for Enum.valueOf (which calls Enum.getConstantDirectory) to String.equals.

What are the possible values for CreateParams.Style?

So, I've been playing with trying to create an AppBar program I'm making. Now, the program itself is actually quite simple but I had to borrow some code from a CodeProject project to make it an AppBar.
So, my code is the following:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
[StructLayout(LayoutKind.Sequential)]
struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
enum ABMsg : int
{
ABM_NEW = 0,
ABM_REMOVE,
ABM_QUERYPOS,
ABM_SETPOS,
ABM_GETSTATE,
ABM_GETTASKBARPOS,
ABM_ACTIVATE,
ABM_GETAUTOHIDEBAR,
ABM_SETAUTOHIDEBAR,
ABM_WINDOWPOSCHANGED,
ABM_SETSTATE
}
enum ABNotify : int
{
ABN_STATECHANGE = 0,
ABN_POSCHANGED,
ABN_FULLSCREENAPP,
ABN_WINDOWARRANGE
}
enum ABEdge : int
{
ABE_LEFT = 0,
ABE_TOP,
ABE_RIGHT,
ABE_BOTTOM
}
private bool fBarRegistered = false;
private int uCallBack;
private int whereToPin;
[DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);
[DllImport("USER32")]
static extern int GetSystemMetrics(int Index);
[DllImport("User32.dll", ExactSpelling = true,
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool MoveWindow
(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern int RegisterWindowMessage(string msg);
private void RegisterBar()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
if (!fBarRegistered)
{
uCallBack = RegisterWindowMessage("AppBarMessage");
abd.uCallbackMessage = uCallBack;
uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
fBarRegistered = true;
ABSetPos();
}
else
{
SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
fBarRegistered = false;
}
}
private void ABSetPos()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
abd.uEdge = whereToPin;
if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
{
abd.rc.top = 0;
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
if (abd.uEdge == (int)ABEdge.ABE_LEFT)
{
abd.rc.left = 0;
abd.rc.right = Size.Width;
}
else
{
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
abd.rc.left = abd.rc.right - Size.Width;
}
}
else
{
abd.rc.left = 0;
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
if (abd.uEdge == (int)ABEdge.ABE_TOP)
{
abd.rc.top = 0;
abd.rc.bottom = Size.Height;
}
else
{
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
abd.rc.top = abd.rc.bottom - Size.Height;
}
}
SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);
switch (abd.uEdge)
{
case (int)ABEdge.ABE_LEFT:
abd.rc.right = abd.rc.left + Size.Width;
break;
case (int)ABEdge.ABE_RIGHT:
abd.rc.left = abd.rc.right - Size.Width;
break;
case (int)ABEdge.ABE_TOP:
abd.rc.bottom = abd.rc.top + 100;
break;
case (int)ABEdge.ABE_BOTTOM:
abd.rc.top = abd.rc.bottom - Size.Height;
break;
}
SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref abd);
MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top,
abd.rc.right - abd.rc.left, abd.rc.bottom - abd.rc.top, true);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == uCallBack)
{
switch (m.WParam.ToInt32())
{
case (int)ABNotify.ABN_POSCHANGED:
ABSetPos();
break;
}
}
base.WndProc(ref m);
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= (~0x00C00000); // WS_CAPTION
cp.Style &= (~0x00800000); // WS_BORDER
cp.ExStyle = 0x00000080 | 0x00000008; // WS_EX_TOOLWINDOW | WS_EX_TOPMOST
return cp;
}
}
private void button1_Click(object sender, EventArgs e)
{
whereToPin = (int)ABEdge.ABE_LEFT;
RegisterBar();
}
private void button2_Click(object sender, EventArgs e)
{
whereToPin = (int)ABEdge.ABE_RIGHT;
RegisterBar();
}
}
My two questions are:
What are the possible values cp.Style and how do those values effect the display of the AppBar? (The code to which I refer to is located in the System.Windows.Forms.CreateParams override)
I see they are values such as (~0x00C00000) but I have no idea how they work beyond those specific values and can't seem to find any enumeration of different values.
I'm a rather new, self teaching, programmer who does well by taking examples and molding them to my own uses. Thanks in advance for any help you can provide.
Here you go...
Window Styles
As per the OP's original query, there's also:
Window Class Styles

How can I write code for different mobile keys such as numeric and arrow keys using netbeans J2ME?

hi
i want to know which key user pressed in mobile's keypad.....
here's example code:
package hello;
public class KeyDemoCanvas extends Canvas {
String eventType = "- Press any!";
int keyCode;
public void keyPressed(int keyCode) {
eventType = "pressed";
this.keyCode = keyCode;
repaint();
}
public void keyReleased(int keyCode) {
eventType = "released";
this.keyCode = keyCode;
repaint();
}
public void keyRepeated(int keyCode) {
eventType = "repeated";
this.keyCode = keyCode;
repaint();
}
protected void paint(Graphics g) {
g.setGrayScale(255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setGrayScale(0);
int y = 0;
// y = write (g, y, "Key "+ eventType);
if (keyCode == 0) {
return;
}
y = write(g, y, "Char/Code: " + ((keyCode < 0) ? "N/A" : ""
+ (char) keyCode) + "/" + keyCode);
y = write(g, y, "Name: " + getKeyName(keyCode));
String gameAction;
switch (getGameAction(keyCode)) {
case LEFT:
gameAction = "LEFT";
break;
case RIGHT:
gameAction = "RIGHT";
break;
case UP:
gameAction = "UP";
break;
case DOWN:
gameAction = "DOWN";
break;
case FIRE:
gameAction = "FIRE";
break;
case GAME_A:
gameAction = "GAME_A";
break;
case GAME_B:
gameAction = "GAME_B";
break;
case GAME_C:
gameAction = "GAME_C";
break;
case GAME_D:
gameAction = "GAME_D";
break;
default:
gameAction = "N/A";
}
write(g, y, "Action: " + gameAction);
}
public int write(Graphics g, int y, String s) {
g.drawString(s, 0, y, Graphics.LEFT | Graphics.TOP);
return y + g.getFont().getHeight();
}
}
Use Canvas.getGameAction(keyCode) and then compare with Canvas.UP, Canvas.DOWN etc. Have a look at this.

Resources