Beginner Question | The use of modulus in this simple code example.
Hello everyone,
I am just beginning to learn Java and have started reading "Java Programming for the absolute beginner". It is quite a old book but seems to be doing the trick, mainly.
There is a code example which I follow mostly but the use of the modulus operator in the switch condition doesn't make sense to me, why is it used? Could someone shed some light on this for me?
import java.util.Random;
public class FortuneTeller {
public static void main(String args[]) {
Random randini = new Random();
int fortuneIndex;
String day;
String[] fortunes = { "The world is going to end :-(.",
"You will have a HORRIBLE day!",
"You will stub your toe.",
"You will find a shiny new nickel.",
"You will talk to someone who has bad breath.",
"You will get a hug from someone you love.",
"You will remember that day for the rest of your life!",
"You will get an unexpected phone call.",
"Nothing significant will happen.",
"You will bump into someone you haven't seen in a while.",
"You will be publicly humiliated.",
"You will find forty dollars.",
"The stars will appear in the sky.",
"The proper authorities will discover your secret.",
"You will be mistaken for a god by a small country.",
"You will win the lottery!",
"You will change your name to \"Bob\" and move to Alaska.",
"You will discover first hand that Bigfoot is real.",
"You will succeed at everything you do.",
"You will learn something new.",
"Your friends will treat you to lunch.",
"You will meet someone famous.",
"You will be very bored.",
"You will hear your new favorite song.",
"Tomorrow... is too difficult to predict" };
System.out.println("\nYou have awakened the Great Randini...");
fortuneIndex = randini.nextInt(fortunes.length);
switch (randini.nextInt(7) % 7) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Tomorrow";
System.out.println("I, the Great Randini, know all!");
System.out.println("I see that on " + day);
System.out.println("\n" + fortunes[fortuneIndex]);
System.out.println("\nNow, I must sleep...");
}
randini.nextInt(7) % 7randini.nextInt(7) returns a value in the range 0 <= x < 7, right? (Check the API!) And:
0 % 7 == 0
1 % 7 == 1
2 % 7 == 2
3 % 7 == 3
4 % 7 == 4
5 % 7 == 5
6 % 7 == 6Looks like superfluous code to me. Maybe originally they wrote:
randini.nextInt() % 7Note this code has problems, because, for example -1 % 7 == -1
Similar Messages
-
What's wrong with this simple code?
What's wrong with this simple code? Complier points out that
1. a '{' is expected at line6;
2. Statement expected at the line which PI is declared;
3. Type expected at "System.out.println("Demostrating PI");"
However, I can't figure out them. Please help. Thanks.
Here is the code:
import java.util.*;
public class DebugTwo3
// This class demonstrates some math methods
public static void main(String args[])
public static final double PI = 3.14159;
double radius = 2.00;
double area;
double roundArea;
System.out.println("Demonstrating PI");
area = PI * radius * radius;
System.out.println("area is " + area);
roundArea = Math.round(area);
System.out.println("Rounded area is " + roundArea);Change your code to this:
import java.util.*;
public class DebugTwo3
public static final double PI = 3.14159;
public static void main(String args[])
double radius = 2.00;
double area;
double roundArea;
System.out.println("Demonstrating PI");
area = PI * radius * radius;
System.out.println("area is " + area);
roundArea = Math.round(area);
System.out.println("Rounded area is " + roundArea);
Klint -
Standard for the use of session variable in webpart code.
Hi,
Why we should avoid using of session variables while writing code?
Is it not a standard?
Thanks,
Akhilesh Rao
Akhilesh RaoOn the face of it, Session is ideal for this, however this is SharePoint and the obvious isn't always the best.
You'd need to do the calculation about memory usage and number of concurrent users to ensure it really is a viable option in Production.
If it isn't viable, or wouldn't scale to possible future usage what would you do? Then you need to ask if it's really necessary to move between pages? If the user needs to move through a dialog for example, that could be hosted on a single page which might
have different controls or sections made visible as the user progressed through the use case.
Passing data between pages in SharePoint is a lot more difficult than it should be. Sometimes it's best to stay put, and certainly safer than using Session if you're really not sure if Session will stop your solution from scaling.
Always remember, SharePoint might be hosted on ASP.NET but the design considerations are significantly different than if this were a pure ASP.NET application.
w: http://www.the-north.com/sharepoint | t: @JMcAllisterCH | YouTube: http://www.youtube.com/user/JamieMcAllisterMVP -
How to invoke jdb for this simple code
up to now i have been debugging by looking at the code, could someone please tell me how
to invoke jdb for the following example, and how would i look at the local values within x & y
(without having to rely on JOptionPane):
//pg73 ex2.16 The x value input must be larger than the y value
import javax.swing.JOptionPane;
public class ex2_11
public static void main(String args[])
int x =2, y=3;
JOptionPane.showMessageDialog( null,
"a x= " x "\n " +
"b the value of x+x is " + (x+x) + "\n " +
"c x= " + "\n " +
"d " + (x+y) + "= " + (y+x),
"Results",JOptionPane.PLAIN_MESSAGE);
System.exit(0);I think I have already answered this question somewhere else, but I will reiterate it here.
If you have compile errors in your source code (i.e. you left the semi-colon off at the end of a statement), a class file will not get generated.
What you have done is the following:
1. created a working java source file
2. compiled that file and generated a class file
3. then changed the working source file and introduced a compiler error (i.e. you left the semi-colon off at the end of a statement)
4. then attempted to compile the file (with javac), but due to the compiler error a new class file did not get generated (therefore the old class file from the previous compile still resides on your machine).
5. Then you ran jdb on the old previously generated class file.
To confirm what I am saying is true. Delete the class file, then try to generate it again after introducing your compiler error. A new class file will not get generated and therefore you won't be able to use jdb (as jdb requires the class files).
Hope this helps (and gets me the duke dollars),
Tim -
Beginner question about using selection tools (Mac OS X 10.6 user)
I click on, say, Magnetic Lasso and it does its thing. But, in true Sorcerer's Apprentice fashion, it keeps on going and going. Two questions: how to stop the tool, and how to correct the deviant strokes? To stop ML, I click Command + D and nothing happens. I choose Deselect and nothing happens. Also, I am trying to select 2 discontinuous regions in the photo. How to do that? Thanks!
When you double click, it should finish up the selection. You can use the selection brush to tidy up (Option-drag to remove areas.)
To add more areas hold down shift as you select or turn on the add to selection square in the options bar if the tool has it. -
My $20 to the person who can write this simple script for Fission
Here is what I need to automate. I don't care if it's an Apple Script, or an Automator work flow - whatever - just so it will work with my present setup. Once I test it and it works, I'll send $20 to the first person who can help me.
Script needs to apply to each (and every) MP3 file in a selected folder:
Open the first file with Fission v1.6.6 (from: www.rogueamoeba.com)
Select all
Normalize
Save audio (in same folder)
A warning dialog pops up: "File already exists..." -- answer with "Replace"
Close file
Repeat for next file in the folder, until every file has been Normalized
End script when the last file in folder has been Normalized
I don't mind finding the folder (which will be in my iTunes Library), and then starting the set of actions on the folder but I definitely don't want to be required to take any additional action on each and every file.
I'm presently running Fission v1.6.6 under MacOS 10.4.11 on a PPC desktop, so it needs to work in that environment.
Note that the latest version of Fission requires MacOS 10.5 - I can't use any script that requires that version. Rogue Amoeba's Legacy software page (http://www.rogueamoeba.com/legacy/) shows Fission v1.6.8 as working with 10.4, but that contradicts the Version History for Fission which shows 1.6.6 as the last one for 10.4 - still investigating.Pierre L.
Thanks for the effort!
First, I can clarify this: Rogue Amoeba confirms that I can use the version 1.6.8 of Fission located on their Legacy page with my OS version 10.4.11, so I've upgraded from 1.6.6 to 1.6.8. Seems to be working OK.
Next, let me apologize for being mostly ignorant about all things AppleScript. I'm really in over my head, here, because I've not used the ScriptEditor for more than a few minutes before today.
What I've done so far:
I checked the box in the Universal Access preferences pane to enable access for assistive devices.
I copied your script from this forum and pasted it into Script Editor.
I've Compiled your script, then "Saved As" an "Application" on my Desktop.
When I double click the icon for the saved script (which ends in xyz.app), a navigation window appears, which I used to select a test folder on my desktop.
When I Choose the test folder, Fission launched, and selected the whole file, as expected. Then I get an error:
"NSReceiverEvaluationScriptError: 4" - with buttons to "Edit" or "OK"
Thinking it might be a timing error, I edited the delays:
set theFolder to choose folder
tell application "Fission" to activate
tell application "Finder"
set theApp to POSIX path of (get file of process "Fission")
set theFiles to document files of theFolder
repeat with thisFile in theFiles
open thisFile using POSIX file theApp
tell application "System Events" to tell process "Fission"
delay 18 -- adjust if necessary
keystroke "a" using command down -- Select All
delay 2 -- adjust if necessary
click menu item "Normalize Selection" of menu 1 of menu bar item 7 of menu bar 1
delay 4 -- adjust if necessary
keystroke "s" using {shift down, command down} -- Save Audio…
delay 3 -- adjust if necessary
keystroke return -- Save
delay 2 -- adjust if necessary
click button "Replace" of sheet 1 of window "Save Audio"
end tell
end repeat
end tell
tell application "Fission" to quit -- optional
... Compiled, and Saved again.
Now, the script runs up to the point where it should answer the Save pop-up window: "File already exists..." with the keystroke to "Replace" - but the script stops there, with the same error: "NSReceiverEvaluationScriptError: 4"
Bottom line: so far, I've been able to get the first mp3 file in my test folder Normalized, but not Saved. Any suggestions? -
Can't figure out how to solve the decimal point bug in this calculator code
Hi guys, I'm new in flash and is currently learning how to build a simple calculator with multipliers (plus,minus,multiple,divide,decimal point and change sign) but I'm stuck on the decimal point and change sign.
var multiplier_old:Number = 10;
var multiplier_new:Number = 1;
// .: Sets the multipliers so that new input numbers become decimals of a lower unit column
action_point.addEventListener(MouseEvent.MOUSE_DOWN, function():void {
multiplier_old = 1;
multiplier_new = 0.1;
point = true;
// Takes intput from the input_ buttons and adds it to the input after applying the multipliers.
// If `point` is true then the multiplier_new is divided by 10, also as described.
function inputNumber(n:Number):void {
input = input * multiplier_old + n * multiplier_new;
if (point) {
multiplier_new *= 0.1;
trace(multiplier_new);
output_txt.text = input.toString();
Decimal point
The problem is that when I input 2.7 in the calculator, it will display the values in output_txt correctly. But then when I input 2.78, it will display 2.780000000000000000000000002. This will also happen to other numbers if the input is too big.
What I want is just 2.78. How do I change the codings to make 2.780000000000000000000000002 become 2.78?
Change sign
Any tips on how to start on this one?
Thanks for your time,
ZainuI think you misunderstand what I mean. The weird decimal doesnt comes out after I press the 'equals' sign. It comes out when im just pressing on the caculator number buttons
First I click the no.2 button and then the decimal point button.
So the caculation output display will show
2.
after that I press the no.7 button
2.7
and then no.8 button. It appears like
2.7800000000000000002
This is the code I use when the user press the decimal point button.
// .: Sets the multipliers so that new input numbers become decimals of a lower unit column
action_point.addEventListener(MouseEvent.MOUSE_DOWN, function():void {
multiplier_old = 1;
multiplier_new = 0.1;
point = true;
// Takes intput from the input_ buttons and adds it to the input after applying the multipliers in the method described above.
// If `point` is true then the multiplier_new is divided by 10, also as described.
function inputNumber(n:Number):void {
input = input * multiplier_old + n * multiplier_new;
if (point) {
trace(multiplier_new.toFixed(3));
multiplier_new *= 0.1;
//trace(multiplier_new);
output_txt.text = input.toString();
I think there is some code wrong in this function that makes this weird problem. I tried putting toFixed method but it's still not working.
Sorry for this long reply but I have to try my bestto explain with my bad english. -
What is the problem with this simple code?
import javax.swing.*;
public class TestThread extends JApplet implements Runnable
JPanel jp;
JLabel jb;
public void init()
jp=new JPanel();
jb=new JLabel("Botton");
getContentPane().add(jp);
jp.add(jb);
public static void main(String args[])
new TestThread().start();
public void run()
System.out.println("Jaison");
Y it not working...help me
contd............
<html>
<head>
</head>
<applet
code=TestThread.class
width=1450
height=1680>
</applet>
</html>Status bar says
Applet TestThread StartedYou do know that main isn't used by applets? It will not be executed by the browser.
Kaj -
Urgent Please tell the use of Event Handler ,how to code in netbeans?
where to write code in netbeans?
Also how to write Event Handlers on buttons like save ?Start with this page:
C:\Program Files\netbeans-5.5\nb5.5\docs\quickstart_jump.html -
Help me to run this simple RMI example
When i m running this example in standalone pc it works but while running on to different pc it gives error though I m giving the IP address from client of server.. If anyone can help me out plz help.
Code:
ReceiveMessageInterface
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote
void receiveMessage(String x) throws RemoteException;
Server code:
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends java.rmi.server.UnicastRemoteObject
implements ReceiveMessageInterface
int thisPort;
String thisAddress;
Registry registry; // rmi registry for lookup the remote objects.
// This method is called from the remote client by the RMI.
// This is the implementation of the �ReceiveMessageInterface�.
public void receiveMessage(String x) throws RemoteException
System.out.println(x);
public RmiServer() throws RemoteException
try{
// get the address of this host.
thisAddress= (InetAddress.getLocalHost()).toString();
catch(Exception e){
throw new RemoteException("can't get inet address.");
thisPort=3232; // this port(registry�s port)
System.out.println("this address="+thisAddress+",port="+thisPort);
try{
// create the registry and bind the name and object.
registry = LocateRegistry.createRegistry( thisPort );
registry.rebind("rmiServer", this);
catch(RemoteException e){
throw e;
static public void main(String args[])
try{
RmiServer s=new RmiServer();
catch (Exception e) {
e.printStackTrace();
System.exit(1);
Client code:
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient
static public void main(String args[])
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String text=args[2];
System.out.println("sending "+text+" to "+serverAddress+":"+serverPort);
try{
// get the �registry�
registry=LocateRegistry.getRegistry(
serverAddress,
(new Integer(serverPort)).intValue()
// look up the remote object
rmiServer=
(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rmiServer.receiveMessage(text);
catch(RemoteException e){
e.printStackTrace();
catch(NotBoundException e){
e.printStackTrace();
}When we compile with rmic skeleton and stub get created then we hav to place stub at each client ???Your remote client applcation need only _Stub.class fiels.
Is there way by which we can know how many clients are connected to the
server and there IP address, can anyone give the code... I guess that you should use a RMI login/logout method to register/unregister your client connection information into a databse or a simple static Hashtable(Vector) object. -
Plz help me in this simple code
hi every one
I try to generate a serial number the column ia varchar2
I need to know the maxium length for the data in this column
I try to write this code
declare
max_l number;
begin
select max(length(ITEM_NO)) into max_l from COMPANY_ITEMS;
end if;
this code give me value in toad but in form give me error
how can I over comee at this errorHi,
declare
max_l number;
begin
select max(length(ITEM_NO)) into max_l from COMPANY_ITEMS;
end if;The problem in your code is that you are using *"end if;"* instead of *"end;"*
this code give me value in toad but in form give me error Not sure how it worked in toad, it will never work even in toad.
Hope this helps.
Best Regards
Arif Khadas -
Facing syntax error in this simple code snippet
select case
when to_number (to_char(sysdate,'mm')) < 7
then (to_number(to_char(sysdate,'yyyy')) - 1)
from dual
--while if in block works fine
declare
year number;
begin
year := to_number(to_char(sysdate,'yyyy'));
if (to_number(to_char(sysdate,'mm')) < 7) then
year := year - 1;
end if;
dbms_output.put_line('year = '|| year);
end;You can have:
-- 1 case expression
-- 1.2 searched case expressions
-- 2 simple case statement
-- 2.1 searched case statement
In your case you need the first one(-- 1 case expression ), because you return an expression.
Indeed a simple case statement let you choose a sequence of PL/SQL statements to execute. This follows another syntax.
It's not always true this statements
In PL/SQL you would use "END CASE". For this reason I can quietly show you that I can even use 'case expression' in PL/SQL, without end case:
DECLARE
subtype TTempWord is varchar2(20); -- good notation :-)
valToCompare constant tTempWord:='test';
temp tTempWord ;
temp2 tTempWord ;
--- start locals------- ;-)
procedure Compare_Display -- with no parameters just for this dummy test!
is
begin
dbms_output.put_line('Word to compare:'||valToCompare);
dbms_output.put_line('temp:'||temp);
dbms_output.put_line('temp2:'||nvl(temp2,'not assigned'));
temp2:= case temp when valToCompare then 'identic ' else 'NOT identic' end ; -- I'm not using *'END CASE'*
dbms_output.put_line(' --- after the assignation --->');
dbms_output.put_line('temp:'||temp);
dbms_output.put_line('temp2:'||temp2);
dbms_output.new_line;dbms_output.new_line;
end;
--- end locals------- ;-)
BEGIN
temp:='testttt';
Compare_Display ;
temp:=valToCompare;
temp2:='';
Compare_Display ;
END;--output
Word to compare:test
temp:testttt
temp2:not assigned
--- after the assignation --->
temp:testttt
temp2:NOT identic
Word to compare:test
temp:test
temp2:not assigned
--- after the assignation --->
temp:test
temp2:identic
PS:for more explanations related to all the cases you could look for at http://tahiti.oracle.com/
Edited by: zep111 on Apr 28, 2011 11:25 AM -
Why this simple code doesn't work?????
i get error "java.sql.SQLException: Operation not allowed after ResultSet closed "
try{
Class.forName("com.mysql.jdbc.Driver");
Connection dbcon = DriverManager.getConnection("jdbc:mysql://localhost:3306/db?user=user&password=pasw&useUnicode=true&characterEncoding=utf-8");
String query = "SELECT * FROM data where parent_id='xxsds^1'";
Statement statement = dbcon.createStatement();
ResultSet rs = statement.executeQuery(query);
while(rs.next())
String name = rs.getString("name");
String query2 = "SELECT * FROM data where parent_id='"+name+"'";
statement.execute(query2);
ResultSet rs2 = statement.getResultSet();
while(rs2.next())
String name1 = rs2.getString("name");
catch(Exception ex){out.println(ex);}thanks a lotYou need to use two separate statments if you're going to interleave the queries like that. I'd think you could get by with a single query and a join though, but I didn't actually look at what your queries are doing.
Also, you should use PreparedStatement, a "?" parameter, and PS's setString method, rather than a plain old Statement where you have to maually handle string quoting. -
Could someone check this simple code.... pleaseee
while (in.ready()){
int i = 0;
line = in.readLine();
if(line.equals("NAMES"))
line = in.readLine();
if (!line.equals("RESULTS")) {
if(!line.equals("NAMES")) {
teamVector.add(i,new Team(line));
i++;
if(line.equals("RESULTS"))
break;
} //closing first in.ready
[/code[
My question is ... at one point when reading in from the file the line = in.readling() will be a string "NAMES"... does that line then get added to the vector ??
WELL IT DOES !!!!!!!!!!
AND I CAN BELIEVE MY EYES !!! HOW CAN IT>>> MY IF"S ARE CORRECT OR GOD TOOK AWAY MY LOGIC !
Please help
Many Thanks to all who do !Repost....
while (in.ready()){
int i = 0;
line = in.readLine();
if(line.equals("NAMES"))
line = in.readLine();
if (!line.equals("RESULTS")) {
if(!line.equals("NAMES")) {
teamVector.add(i,new Team(line));
i++;
if(line.equals("RESULTS"))
break;
} //closing first in.readyMy question is ... at one point when reading in from the file the line = in.readling() will be a string "NAMES"... does that line then get added to the vector ??
WELL IT DOES !!!!!!!!!! AND I CAN BELIEVE MY EYES !!! HOW CAN IT ???
MY IF"S ARE CORRECT OR GOD TOOK AWAY MY LOGIC !
Please help
Many Thanks to all who do ... i really appreciate it you will save me many bad tempers.... -
Why do we need downcasting in Java? What is the use of it?
Why do we need downcasting in Java? What is the use of it?
here's an example of a valid downcast.
class Dog {}
class Dogma extends Dog {}
class Dogmatic extends Dog {}
Dog dogwood = new Dogma(); // a Dogma object is upcast to a Dog
Dogma bush = (Dogma) dogwood; // a Dogma object is downcast from a Dog
You cannot upcast a Dogmatic to a Dog and then downcast it to a Dogma. You also cannot downcast a Dog to a Dogma. In the working example, above, the dogwood references a Dogma, so you can downcast the Dogma.
and one more example
If you have a class hierarchy where class B extends class A (B is a specialization of A) you can use B in the place of A since B supports all the operations that B does. This is called polymorphism.
When you use an object of type B in place of A you actually do a up-cast, meaning you make the object of type B look like an object of type A (a less specific class type).
What you are asking about is down-casting which is making an object be of a more specific type, i.e. transforming an object of type A to type B. Is is only allowed if the object was actually created as a type B.
This is allowed (line 2 is a down-cast):
A a = new B();
B b = (B)a;
Maybe you are looking for
-
I used to sync my iphone to a laptop which is no longer in my posession. I am now looking to start over and have a new itunes on my pc with no music on it. When i connect my iphone up to the new itunes it doesn't recognise it or sync - can anyone hel
-
HP 5524 Wireless does not work after firmware upgrade
HI, I have just purchased an HP5524. After initial problems setting up the WPA key from the printer screen, I connected via USB, found the printer and swapped to wireless successfuly. I then installed the printer software on all my computers at home
-
dear gurus, i am having some queries regarding number ranges,. in number ranges of production orders i am finding.. number range group with check box under that i find the order types.Say(1234 -to9999) pp01 pp04 zx01 .My requir
-
Can I use Ipad2 with wifi +3G with an Alltel Motorola MilestoneX 3g hotspot phone?
Alltel is my mobile service provider, and they are now offering the Motorola Milestone X running Android 2.2; this phone can function as a 3G hotspot. If I have an Ipad2 with wifi+3g, and I turn the hotspot functionality of the phone on, can my Ipad
-
Hello everyone, I'm on a Mac OSX 10.8.5 and I am trying to follow these instructions: AMS Financial Aid Forms by Rachael Arestad on Prezi using Adobe Reader 11.0.10. However, there are a couple problems that come up. 1) I can't print the PDF as a PDF