|
Hi and thanks for looking,
Just started to learn Java and after reading various tutorials came up with this simple tables program.
My question, is it as it should be? I mean it works OK but is it coded correctly?
import java.util.Scanner;
public class MyTables {
public static void main(String[] args) {
int secondNum, answerNum;
Scanner sc = new Scanner(System.in);
System.out.println("Type a number:");
secondNum = sc.nextInt();
for (int firstNum = 1; firstNum <= 12; firstNum ++) {
answerNum = firstNum * secondNum;
System.out.println(firstNum + " x " + secondNum + " = " + answerNum);
}
}
}
|
|
|
|
|
Looks OK and works, so that should be enough. You may like to use formatting on your output so all table entries are on the same column - currently the x and beyond is shifted right from 10 onwards.
|
|
|
|
|
Thanks for the reply and for the suggestion re formatting.
|
|
|
|
|
books examples of precedures stored for sqlserver 
|
|
|
|
|
|
Search on Amazon. There are tons of them.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
Question: Write a Java program for a 2-dice game. This game will roll the two dice together for 100 times. In each time, it will display the face values from both dice. The program will count how many times (out of these 100 attempts) did the two dice generate a total point of 10 or above, and display the result at the end. (10 pts) See the execution example above.
Requirements:
a) In this question, use the Random class and its object to simulate dice rolling. Make sure your dice will generate integer values in the range of 1 - 6.
b) You will need two counter variables. One is to count for how many attempts you have rolled the two dice – to control the loop. The other is to count how many times that your two dices gave a total point of 10 or above.
c) Use a WHILE loops in this program. DO NOT USE THE OTHER LOOP METHODS in this question.
d) Your class should be named TwoDiceGame, and your source code file should be named TwoDiceGame.java.
e) Programming styles are always required.
My code:
import java.util.Random;
public class TwoDiceGame {
public static void main(String[] args){
// Declare a counter variable to count the loop time
int count = 0;
int die1, die2;
for(int i=0;i<100;i++)
rNums = new Random(); // create a new object of Random class
int die1 = rNums.nextInt(6)+1;
int die2= rNums.nextInt(6)+1;
if(Die1 + Die2 >= 10);
count ++;
}
System.out.println ("Out of 100 rolls of the two dice, the total of both the dice greater than or equal to 10 was %d times");
}
{
}
Errors:
----jGRASP exec: javac -g TwoDiceGame.java
TwoDiceGame.java:32: error: <identifier> expected
System.out.println ("Out of 100 rolls of the two dice, the total of both the dice greater than or equal to 10 was %d times");
^
TwoDiceGame.java:32: error: illegal start of type
System.out.println ("Out of 100 rolls of the two dice, the total of both the dice greater than or equal to 10 was %d times");
^
TwoDiceGame.java:34: error: class, interface, or enum expected
{
^
3 errors
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
Can someone please help me revise this code? I have this due by tonight and have tried everything to fix it.
|
|
|
|
|
The call to System.out.println is outside of the main method, which is incorrect. Using proper indentation helps to see such basic errors.
It should be
import java.util.Random;
public class TwoDiceGame {
public static void main(String[] args){
int count = 0;
int die1, die2;
for(int i=0;i<100;i++) {
rNums = new Random();
int die1 = rNums.nextInt(6)+1;
int die2= rNums.nextInt(6)+1;
if(Die1 + Die2 >= 10);
count ++;
}
System.out.println ("Out of 100 rolls of the two dice, the total of both the dice greater than or equal to 10 was %d times");
}
}
|
|
|
|
|
I also just noticed that the instructions tell you to use a "while" loop and not any other type.
|
|
|
|
|
Try to use another loop...
|
|
|
|
|
|
Here's what I came up with not sating it's the correct way as I am only just starting with Java but it works.
import java.util.Random;
public class TwoDiceGame {
public static void main(String[] args){
int count = 0, total = 0;
for(int i=0;i<100;i++){
Random rNums = new Random();
int rNums_die1 = rNums.nextInt(6)+1;
int rNums_die2 = rNums.nextInt(6)+1;
if(rNums_die1 + rNums_die2 >= 10){
total ++;
count ++;
}
else{
count++;
}
}
System.out.println ("Out of 100 rolls of the two dice, the total of both the dice greater than or equal to 10 was " + total + " times");
}
}
|
|
|
|
|
Nice but ...
... you should create the Random object once only, before the for loop. Random classes tend to be pseudo rather than 'true' random number generators, and as such will generally produce the same sequence each time. You can improve on this by adding a seed value to the constructor as described at Random (Java Platform SE 8 )[^], but it is still best to create it only once, before using it in a loop.
|
|
|
|
|
Thanks again Richard, as I have said I am only starting out with Java and saw this post so thought it would give me something to have a go at. Will look at the link you have provided.
|
|
|
|
|
If you also want to see some excellent learning materials then take a look at The Java™ Tutorials[^].
|
|
|
|
|
Will look at the tutorials.
Tried the random seed and always got the same number every time I ran the program
So did this and it seems to work, at least I get different result each time.
Random rnd = new Random();
rnd.setSeed(System.currentTimeMillis());
|
|
|
|
|
Hello Everyone! I have found some code and developed a database that you can enter a student's name and their parents phone number. However, I am stuck. I need the data from the SQL database to populate and spinner, but I don't even know where to begin with coding that. I would appreciate any help that could be given. Here is the code I am currently using (I did get this code online and tailored it to work with my version of Android Studio. (I am using version 3.5)
The following code is in MainActivity.java
package codebind.example.sqliteoperations;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText Name, Pass , updateold, updatenew, delete;
myDbAdapter helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name= (EditText) findViewById(R.id.editName);
Pass= (EditText) findViewById(R.id.editPass);
updateold= (EditText) findViewById(R.id.editText3);
updatenew= (EditText) findViewById(R.id.editText5);
delete = (EditText) findViewById(R.id.editText6);
helper = new myDbAdapter(this);
}
public void addUser(View view)
{
String t1 = Name.getText().toString();
String t2 = Pass.getText().toString();
if(t1.isEmpty() || t2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Both Name and Password");
}
else
{
long id = helper.insertData(t1,t2);
if(id<=0)
{
Message.message(getApplicationContext(),"Insertion Unsuccessful");
Name.setText("");
Pass.setText("");
} else
{
Message.message(getApplicationContext(),"Insertion Successful");
Name.setText("");
Pass.setText("");
}
}
}
public void viewdata(View view)
{
String data = helper.getData();
Message.message(this,data);
}
public void update( View view)
{
String u1 = updateold.getText().toString();
String u2 = updatenew.getText().toString();
if(u1.isEmpty() || u2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Data");
}
else
{
int a= helper.updateName( u1, u2);
if(a<=0)
{
Message.message(getApplicationContext(),"Unsuccessful");
updateold.setText("");
updatenew.setText("");
} else {
Message.message(getApplicationContext(),"Updated");
updateold.setText("");
updatenew.setText("");
}
}
}
public void delete( View view)
{
String uname = delete.getText().toString();
if(uname.isEmpty())
{
Message.message(getApplicationContext(),"Enter Data");
}
else{
int a= helper.delete(uname);
if(a<=0)
{
Message.message(getApplicationContext(),"Unsuccessful");
delete.setText("");
}
else
{
Message.message(this, "DELETED");
delete.setText("");
}
}
}
}
The following code is in myDbAdapter.java
package codebind.example.sqliteoperations;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class myDbAdapter {
myDbHelper myhelper;
public myDbAdapter(Context context)
{
myhelper = new myDbHelper(context);
}
public long insertData(String name, String pass)
{
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME, name);
contentValues.put(myDbHelper.MyPASSWORD, pass);
long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues);
return id;
}
public String getData()
{
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID,myDbHelper.NAME,myDbHelper.MyPASSWORD};
Cursor cursor =db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null);
StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext())
{
int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
String password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD));
buffer.append(cid+ " " + name + " " + password +" \n");
}
return buffer.toString();
}
public int delete(String uname)
{
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] whereArgs ={uname};
int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+" = ?",whereArgs);
return count;
}
public int updateName(String oldName , String newName)
{
SQLiteDatabase db = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME,newName);
String[] whereArgs= {oldName};
int count =db.update(myDbHelper.TABLE_NAME,contentValues, myDbHelper.NAME+" = ?",whereArgs );
return count;
}
static class myDbHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME = "myDatabase";
private static final String TABLE_NAME = "myTable";
private static final int DATABASE_Version = 1;
private static final String UID="_id";
private static final String NAME = "Name";
private static final String MyPASSWORD= "Password";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
Message.message(context,""+e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
Message.message(context,""+e);
}
}
}
}
The following code is in Message.java
package codebind.example.sqliteoperations;
import android.content.Context;
import android.widget.Toast;
public class Message {
public static void message(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
The following code is in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4B1414">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Student Name"
android:textColor="#FFFFFF"
android:textSize="18sp"
android:textStyle="bold|italic" />
<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:ems="10"
android:gravity="center_vertical|center"
android:hint="Enter Name"
android:inputType="textPersonName"
android:textColor="#FFFFFF"
android:textStyle="bold|italic" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editName"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="13dp"
android:gravity="center"
android:hint="Enter Password"
android:text="Parent Number"
android:textColor="#FFFFFF"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button"
android:layout_alignEnd="@+id/button4"
android:layout_alignRight="@+id/button4"
android:layout_alignBottom="@+id/button"
android:onClick="viewdata"
android:text="View Data"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editPass"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="28dp"
android:layout_marginLeft="28dp"
android:layout_marginTop="23dp"
android:onClick="addUser"
android:text="Add User"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_alignStart="@+id/button4"
android:layout_alignLeft="@+id/button4"
android:layout_marginTop="13dp"
android:onClick="update"
android:text="Update"
android:textStyle="normal|bold" />
<EditText
android:id="@+id/editText6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button4"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_toStartOf="@+id/button2"
android:layout_toLeftOf="@+id/button2"
android:ems="10"
android:freezesText="false"
android:hint="Enter Name to Delete Data"
android:inputType="textPersonName" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:layout_marginBottom="41dp"
android:onClick="delete"
android:text="Delete"
android:textStyle="normal|bold"
tools:ignore="RelativeOverlap" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="7dp"
android:layout_marginLeft="7dp"
android:layout_marginTop="47dp"
android:ems="10"
android:hint="Current Name"
android:inputType="textPersonName"
android:textColor="#FFFFFF"
android:textSize="14sp"
android:textStyle="bold|italic" />
<EditText
android:id="@+id/editPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="11dp"
android:ems="10"
android:gravity="center_vertical|center"
android:hint="Enter Number"
android:inputType="textPassword"
android:textAllCaps="false"
android:textSize="18sp"
android:textStyle="normal|bold" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/editText3"
android:layout_alignLeft="@+id/editText3"
android:layout_alignTop="@+id/button3"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="New Name"
android:inputType="textPersonName"
android:textSize="14sp"
android:textStyle="bold|italic" />
</RelativeLayout>
Thanks you for all your help!
|
|
|
|
|
|
Thank you. How would I go about doing that? I am fairly new to android studio and this is all new to me.
|
|
|
|
|
|
|
Hi Guys,
This is my first post in this community. And I hope I am not screwing up.
Anyways I built a package to process Json data as a string into objects as nodes stored in nodes in a tree. It is far from complete, but the parsing and node tree building methods are set and the manager class is commenting.
This is also important to me as I am building a portfolio, and I i would be grateful if someone can take another look to see if anything can be done more efficiently and possible let me know where i went wrong with commenting and examples of how you would do it.
Anyways the main class link in github is bellow:
JVJsonManager/Json.java at master · Clowcadia/JVJsonManager · GitHub[^]
|
|
|
|
|
Sorry, this forum is for technical questions. Also, most people here have day jobs so their time is limited. But Java already has built in support for JSON: java json - Google Search[^].
|
|
|
|
|
Thank you for response, I am aware of the existing Json libraries out there, the reason i made my own is to populate my portfolio with something as i think a starter portfolio will tend to end up rewriting the wheel . (I am sure this is the case most of the time anyways, as most application for most functions are already existent). As for this is not the correct community for this, does anyone have suggestions where I could get some advice?
|
|
|
|
|
So i am working on a hacker rank question and able to make it work but in certain cases it takes way too much time
<pre>static long repeatedString1(String u, long n) {
String[] a = u.split("");
int s = a.length;
int t = (int) n;
int r = (t / s) + 1;
String d = new String(new char[t]).replace("\0", u);
String[] m = d.split("");
long p = 0;
if (s == 1) {
p = t;
} else {
for (int i = 0; i < t; i++) {
if (m[i].equals("a")) {
p++;
}
}
}
return p;
}
any sugessions how i can make it fast?
The question is i will given a randon string and i have to count no of "a" in the string where "n" is the no of words that will be repeated.https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup[^]
|
|
|
|
|