Running the following simple program in Netbeans 12 and finding that the print statements won't display until after all data is entered - so there is no prompting before the input request. When using println, it works as expected.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name: ");
String firstName = in.next();
System.out.print("Enter last name: ");
String lastName = in.next();
System.out.print("Enter age: ");
int age = in.nextInt();
System.out.printf("%-16s%-16s%-16s%n", "First Name", "Last Name", "Age");
System.out.printf("%-16s%-16s%-16s%n", firstName, lastName, age);
Related
I am trying to compare two birthdates with the use of user input, but when I try to make them be identical it shows me the result of NOT IDENTICAL but shows the correct date.
public static void main(String[] args) throws ParseException {
Scanner console =new Scanner(System.in);
Person p1=new Person();
System.out.println("Enter the name: ");
String name=console.nextLine();
p1.setName(name);
System.out.println("Enter the birthday: <dd/MM/yyyy>");
String bdate=console.next();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date MyDate=sdf.parse(bdate);
p1.setMyDate(MyDate);
Person p2=new Person();
System.out.println("Enter the name: ");
name=console.next();
p2.setName(name);
System.out.println("Enter the birthday: <dd/MM/yyyy>");
String bdate2=console.next();
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
Date MyDate2=sdf2.parse(bdate2);
p2.setMyDate(MyDate2);
boolean b=p1.equals(p2);
if (b) {
System.out.println("IDENTICAL");
} else {
System.out.println("NOT IDENTICAL");
}
System.out.println(p1);
System.out.println(p2);
console.close();
}
I need to implement an update of the database lying in the assets. User data, namely, in the "favorite" record or not, should be saved.
I already asked a question and they helped me -https://stackoverflow.com/a/53827525/10261947
Everything worked in a test application. But when I transferred the code (exactly the same) to the real application, an error occurs - E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1
Process: rodionova.lyubov.brodsky, PID: 4196
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:784)
Caused by: java.lang.IllegalArgumentException: the bind value at index 4 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:169)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:205)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1397)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1239)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1110)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1278)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.insertCorePoem(PoemsDbHelper.java:121)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.getNewPoems(PoemsDbHelper.java:90)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.onUpgrade(PoemsDbHelper.java:41)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:197)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
at rodionova.lyubov.brodsky.db.PoemsProvider.query(PoemsProvider.java:45)
at android.content.ContentProvider.query(ContentProvider.java:1057)
If you do not perform the update, the application is working properly, so I will post only the code DbHelper
public class PoemsDbHelper extends SQLiteAssetHelper {
public static final String DB_NAME = "brodsky.db";
public static final int DBVERSION = 3;
public static final String TBLNAME = "poems_table";
public static final String COL_ID = "id";
public static final String COL_TITLE = "title";
public static final String COl_POEM = "poem";
public static final String COL_SUBJECT = "subject";
public static final String COL_YEARS = "years";
public static final String COL_FAVOURITE = "favorite";
Context mContext;
public PoemsDbHelper(Context context) {
super(context, DB_NAME, null, DBVERSION);
mContext = context;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion)
getNewPoems(mContext, db);
}
private void getNewPoems(Context context, SQLiteDatabase db) {
InputStream is;
OutputStream os;
final String tempNewDbName = "temp_brodsky.db";
int buffersize = 4096;
byte[] buffer = new byte[buffersize];
String newDBPath = mContext.getDatabasePath(tempNewDbName).getPath();
File newDBFile = new File(newDBPath);
if (newDBFile.exists()) {
newDBFile.delete();
}
File newDBFileDirectory = newDBFile.getParentFile();
if (!newDBFileDirectory.exists()) {
newDBFileDirectory.mkdirs();
}
try {
is = context.getAssets().open("databases/" + DB_NAME);
os = new FileOutputStream(newDBFile);
int bytes_read;
while ((bytes_read = is.read(buffer,0,buffersize)) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Ouch updated database not copied - processing stopped - see stack-trace above.");
}
long id = maxid(db) + 1;
SQLiteDatabase newdb = SQLiteDatabase.openDatabase(newDBFile.getPath(),null,SQLiteDatabase.OPEN_READONLY);
Cursor csr = newdb.query(TBLNAME,null,null,null,null,null,null);
long insert_result;
db.beginTransaction();
while (csr.moveToNext()) {
insert_result = insertCorePoem(
db,
id,
csr.getString(csr.getColumnIndex(COL_TITLE)),
csr.getString(csr.getColumnIndex(COl_POEM)),
csr.getString(csr.getColumnIndex(COL_SUBJECT)),
csr.getString(csr.getColumnIndex(COL_YEARS)),
csr.getString(csr.getColumnIndex(COL_FAVOURITE))
);
if (insert_result > 0) {
id++;
}
}
db.setTransactionSuccessful();
db.endTransaction();
csr.close();
newDBFile.delete();
}
public long insertCorePoem(SQLiteDatabase db, long id, String title, String poem, String subject, String years, String favourite) {
String whereclause = COL_TITLE + "=? AND " + COl_POEM + "=? AND " + COL_SUBJECT + "=? AND " + COL_YEARS + "=?";
String[] whereargs = new String[]{
title,
poem,
subject,
years
};
Cursor csr = db.query(TBLNAME,null,whereclause,whereargs,null,null,null);
boolean rowexists = (csr.getCount() > 0);
csr.close();
if (rowexists) {
Log.d("INSERTCOREPOEM","Skipping insert of row");
return -2;
}
ContentValues cv = new ContentValues();
cv.put(COL_ID,id);
cv.put(COL_TITLE,title);
cv.put(COl_POEM,poem);
cv.put(COL_SUBJECT,subject);
cv.put(COL_YEARS,years);
cv.put(COL_FAVOURITE,favourite);
Log.d("INSERTCOREPOEM","Inserting new column with id " + String.valueOf(id));
return db.insert(TBLNAME, null, cv);
}
private long maxid(SQLiteDatabase db) {
long rv = 0;
String extractcolumn = "maxid";
String[] col = new String[]{"max(" + COL_ID + ") AS " + extractcolumn};
Cursor csr = db.query(TBLNAME,col,null,null,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(extractcolumn));
}
csr.close();
return rv;
}
}
I do not understand what is wrong. Identical code works great friend application. I would be grateful for the help.
Your issue is that you likely have a value of null in the years column of a row or rows in the updated database that data is being copied from.
Although you could change the code to handle (skip insertion or use provide a year value) the end result may not be desired. So the most likely fix would be to amend the database to have valid/useful year values.
public class MoviesData {
String Const;
String Your_Rating;
String Date_Rated;
String Title;
String URL;
String Title_Type;
String IMDb_Rating;
String Runtime_mins;
String Year;
String Genres;
String Num_Votes;
String Release_Date;
String Directors;
String filename="ratings.csv";
String ReadData(){
File file=new File(filename).getAbsoluteFile();
file.getAbsolutePath();
String data = null;
try{
Scanner S=new Scanner(file);
S.nextLine();
S.useDelimiter(",\n");
while(S.hasNext())
{
data=data+S.next();
}
S.close();
}
catch(Exception e)
{ JOptionPane.showMessageDialog(null, e.getStackTrace()[0]); }
return data;
//String Data=data.replace(",","-");
ArrayList<MoviesData> MD=new ArrayList<MoviesData>();
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
MoviesData m=new MoviesData();
String L=m.ReadData();
String[] M=L.split(",");
m.Const=M[0]; m.Your_Rating=M[1]; m.Date_Rated=M[2]; m.Title=M[3]; m.URL=M[4]; m.Title_Type=M[5];
m.IMDb_Rating=M[6]; m.Runtime_mins=M[7]; m.Year=M[8]; m.Genres=M[9]; m.Num_Votes=M[10];
m.Release_Date=M[11];m.Directors=M[12];
System.out.println(L);
i field has many , between "" i want to chance it
I have String like this (6.2,108,1990,"Action, Horror, Sci-Fi, Thriller",119935,) want to change the , only between "" not all , i get the String from Scanner CSv file
Well I'm pretty stupid so I can't tell exactly what you want but I can guess, if you are asking how you could put anything into a String, you can convert it into a String, a character will go in since it is compatible, for putting in something like a double or an int you can use the Interger.parseInt() and Double.parseDouble() methods like String new = Double.parseDouble(5); but I am probably not understanding the question so If I did than feel free to ignore this answer.
I am creating an app using SQLite.
It crashes before loading.
I fixed all viable errors and since I do not even get a log info, I am having troubles figuring out the error.
Please help.
SQLHelper
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "MediaDB";
// Media table name
private static final String TABLE_MEDIA = "media";
// Media Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TYPE = "type";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String[] COLUMNS = {KEY_ID,KEY_TYPE,KEY_TITLE,KEY_AUTHOR};
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create media table
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
// create media table
db.execSQL(CREATE_MEDIA_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older media table if existed
db.execSQL("DROP TABLE IF EXISTS media");
// create fresh media table
this.onCreate(db);
}
//ADD MEDIA
public void addMedia(Media media){
//for logging
Log.d("addMedia", media.toString());
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TYPE, media.getType()); // get title
values.put(KEY_TITLE, media.getTitle()); // get title
values.put(KEY_AUTHOR, media.getAuthor()); // get author
// insert
db.insert(TABLE_MEDIA, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// close
db.close();
}
//GET MEDIA
public Media getMedia(int id){
// get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// build query
Cursor cursor =
db.query(TABLE_MEDIA, // table
COLUMNS, // column names
" id = ?", // selections
new String[] { String.valueOf(id) }, // d. selections args
null, // group by
null, // having
null, // order by
null); // limit
// if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// build media object
Media media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
//log
Log.d("getMedia("+id+")", media.toString());
// return media
return media;
}
//GET ALL MEDIA
public List<Media> getAllMedia() {
List<Media> medias = new LinkedList<Media>();
// build the query
String query = "SELECT * FROM " + TABLE_MEDIA;
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// go over each row, build media and add it to list
Media media = null;
if (cursor.moveToFirst()) {
do {
media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
// Add media to media
medias.add(media);
} while (cursor.moveToNext());
}
Log.d("getAllMedia()", medias.toString());
// return media
return medias;
}
//UPDATE
public int updateMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("type", media.getType()); // get title
values.put("title", media.getTitle()); // get title
values.put("author", media.getAuthor()); // get author
// updating row
int i = db.update(TABLE_MEDIA, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selection args
// close
db.close();
return i;
}
//DELETE
public void deleteMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// delete
db.delete(TABLE_MEDIA, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selections args
// close
db.close();
//log
Log.d("deleteMedia", media.toString());
}
}
Media object class
public class Media {
private int id;
private String type;
private String title;
private String author;
public Media(){}
public Media(String type, String title, String author) {
super();
this.type = type;
this.title = title;
this.author = author;
}
//getters & setters
// getting ID
public int getId(){
return this.id;
}
// setting id
public void setId(int id){
this.id = id;
}
// getting type
public String getType(){
return this.type;
}
// setting title
public void setType(String type){
this.type = type;
}
// getting title
public String getTitle(){
return this.title;
}
// setting title
public void setTitle(String title){
this.title = title;
}
// getting author
public String getAuthor(){
return this.author;
}
// setting author
public void setAuthor(String author){
this.author = author;
}
#Override
public String toString() {
return "Media [id=" + id + ", type=" + type + ",title=" + title + ", author=" + author
+ "]";
}
}
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteHelper db = new MySQLiteHelper(this);
/**
* CRUD Operations
* */
// add Media
db.addMedia(new Media("Book", "Android Application Development Cookbook", "Wei Meng Lee"));
db.addMedia(new Media("Book", "Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
db.addMedia(new Media("Book", "Learn Android App Development", "Wallace Jackson"));
// get all media
List<Media> list = db.getAllMedia();
// delete one media
db.deleteMedia(list.get(0));
// get all media
db.getAllMedia();
}
}
There's an error in you table creation:
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
TYPE is not a valid SQLlite Data Type.
Please refer to this page: https://www.sqlite.org/datatype3.html
I'd write your table creation as
String CREATE_MEDIA_TABLE = "CREATE TABLE media (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TEXT, "+
"title TEXT, "+
"author TEXT)";
I want to add a facility in a c# application where i can:
1) Take a collection of objects, and pass it to a powershell script from inside my c# application
2) Have the powershell script make changes to the the list of objects it was passed
3) Return that list of objects back to c#
I have an external class called Message
public class Message
{
public String name { get; set; }
public String from { get; set; }
public String to { get; set; }
public String date { get; set; }
public String subject { get; set; }
public String body { get; set; }
}
I populate the PSDataCollection list class as such:
PSDataCollection<Message> mlist = new PSDataCollection<Message>()
{
new Message { to="user1", from="user2", date = "1/10/2010 12:00:00 AM EST", subject = "hi there" , body = "hi again" },
new Message { to="user1", from="user3", date = "1/10/2010 12:00:00 AM EST", subject = "new messages" , body = "new messages" }
}
In the powershell script we want it to
1) Read each object
2) Adjust the date field by adding 2 hours to it
Implementation issues:
The following code is our attempt at getting it working. The first issue we hit was how to import the Message class from an external DLL.
We tried this: Add-Type "G:\testBAL\bin\Debug\testBAL.dll" but got errors
Any help would be appreciated.
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
PSDataCollection<Message> mlist = new PSDataCollection<Message>()
{
new Message { to="user1", from="user2", date = "1/10/2010 12:00:00 AM EST", subject = "hi there" , body = "hi again" },
new Message { to="user1", from="user3", date = "1/10/2010 12:00:00 AM EST", subject = "new messages" , body = "new messages" }
};
mlist.Complete();
PowerShell ps = PowerShell.Create()
.AddScript("Add-Type G:\testBAL\bin\Debug\testBAL.dll")
.AddCommand("Select-Object");
IAsyncResult async = ps.BeginInvoke<Message>(mlist);
foreach(PSObject result in ps.EndInvoke(async))
{
String to = ((Message)(result.BaseObject)).to;
Console.WriteLine("to=" + to);
}
}
}
}
You can use a PowerShell Runspace to Set and Get variables in a PowerShell Session created in a .NET application. I edited your date parameter and removed the EST so it could be easily be parsed by PowerShell's Get-Date cmdlet.
HTH
Doug
var mlist = new PSDataCollection<Message>()
{
new Message { to="user1", from="user2", date = "1/10/2010 12:00:00 AM", subject = "hi there" , body = "hi again" },
new Message { to="user1", from="user3", date = "1/10/2010 12:00:00 AM", subject = "new messages" , body = "new messages" }
};
var rs = RunspaceFactory.CreateRunspace();
rs.Open();
rs.SessionStateProxy.SetVariable("list", mlist);
var ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddScript(#"
$list | ForEach {
$_.date = (Get-Date($_.date)).AddHours(2)
}
");
ps.Invoke();
var result = rs.SessionStateProxy.GetVariable("list") as PSDataCollection<Message>;
foreach (var item in result)
{
Console.WriteLine(item.date);
}
rs.Close();
From your description it appears you are missing the -Path switch.
You have to specify the -Path when you pass a DLL directly. See reference documentation here ... http://technet.microsoft.com/en-us/library/dd315241.aspx
I've loaded a C# assembly into a PowerShell script and used it like this:
$dllPath = "C:\path\library.dll"
$tmp = [Reflection.Assembly]::LoadFile($dllPath)
$obj = new-object Namespace.LibraryClass()