Getting the below error while executing the code:
Exception in thread "main" h
java.lang.ArrayIndexOutOfBoundsException: 12
at com.java.program.ReverseString.main(ReverseString.java:17)
package com.java.program;
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s= new Scanner(System.in);
System.out.println("Enter Any String for recurssion");
String n = s.next();
System.out.println("The Entered Value is: " + n);
char str[]= n.toCharArray();
for (int i= str.length-1;i >= 0; i++) {
System.out.println(str[i]);
}
}
}
Related
I have many static variables in my application and methods which modify those variables. Please find an example code below. Can somebody tell me how to lock my static variable in the following example. It's not getting locked
using System.Threading;
using System;
namespace ThreadTest
{
public class Program
{
public static void Main(string[] args)
{
MyTest.TestVar = 0;
Thread th = new Thread(ThreadB);
Thread th1 = new Thread(ThreadC);
th1.Start();
Console.WriteLine("Thread B started:");
th.Start();
Console.WriteLine("Thread C started :");
for (int i = 0; i < 10; i++)
{
MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
Console.WriteLine("A " + MyTest.TestVar);
Thread.Sleep(100);
}
Console.WriteLine("Threads completed");
}
public static void ThreadB()
{
lock (MyTest.TestVar)
{
for (int i = 0; i < 10; i++)
{
MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
Console.WriteLine("B " + MyTest.TestVar);
Thread.Sleep(10);
}
}
}
public static void ThreadC()
{
for (int i = 0; i < 10; i++)
{
MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
Console.WriteLine("C " + MyTest.TestVar);
//Thread.Sleep(100);
}
}
}
public class MyTest
{
public static Object TestVar;
}
}
Fiddle here https://dotnetfiddle.net/dBJpo2
Use lock statement for your issue. Use sample code like below.
Declare and instantiate a private object variable in your console app that will be used to lock access to TestVar.
//declare a private variable for locking
private Object obj = new Object() ;
Then, enclose the statement where TestVar is being incremeted by 1 within a lock statement.
//use lock to synchronize access to
//property TestVar
lock (obj)
{
MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
}
After above steps, C# runtime will only allow one thread at a time to execute the line of code that changes the value of TestVar.
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
My problem is that once it starts the loop it just reads the first line on the file and writes it infinitely amount of times.
What I want is for it to go to the next line and so on
(The code is basically what I want but it is not finished)
public class Lab0234
{
public static void main(String [] args) throws FileNotFoundException
{
DecimalFormat two = new DecimalFormat("00.00");
Scanner keyboard = new Scanner(System.in);
Scanner inputFile = new Scanner(new FileReader("Lab02Input.txt"));
double sPrice = inputFile.nextDouble();
double sOwned = inputFile.nextDouble();
double aDiv = inputFile.nextDouble();
double mValue;
double mYield;
mValue = getValue(sPrice, sOwned);
mYield = getYield(sPrice, aDiv);
PrintWriter reportFile = new PrintWriter("Lab02Report.txt");
reportFile.println("Stock Value and Yield Report");
reportFile.println("");
reportFile.print("Stock ");
reportFile.print("Price ");
reportFile.print("Shares ");
reportFile.print("Value ");
reportFile.print("Dividend ");
reportFile.println("Yield");
while(inputFile.hasNext())
{
if (inputFile.hasNext())
{
reportFile.print(" ");
reportFile.print(sPrice+" ");
reportFile.print(sOwned+" ");
getValue(sPrice, sOwned);
reportFile.print(two.format(mValue)+" ");
reportFile.print(aDiv+" ");
getYield(sPrice, aDiv);
reportFile.println(two.format(mYield)+" ");
inputFile.close();
reportFile.close();
}
/*else
{
inputFile.close();
reportFile.close();
}*/
}
//inputFile.close();
//reportFile.close();
}
public static double getValue(double sPrice, double sOwned)
{
//DecimalFormat two = new DecimalFormat("00.00"); //Decimal format
double mValue;
mValue = (sPrice * sOwned);
//System.out.printf("Stock Value is " + mValue);
return mValue;
}
public static double getYield(double sPrice, double aDiv)
{
//DecimalFormat two = new DecimalFormat("00.00"); //Decimal format
double mYield;
mYield = (aDiv * sPrice);
//System.out.printf("\nDividend Yield is " + two.format(mYield));
return mYield;
}
}
You never call next() on your inputFile:
while(inputFile.hasNext())
{
String x = inputFile.next();
if (inputFile.hasNext())
Try do it like this
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null) {
// do somthing
}
br.close();
} catch (Exception e) {
System.out.print("Problem!");
}
I have written the following code and keep running into this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at yournamep3.Yournamep3test.main(Yournamep3test.java:23)
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class Yournamep3test {
public static void main(String[] args) {
// Check if target file exists
File targetFile = new File(args[0]);
try {
PrintWriter out = new PrintWriter(targetFile);
out.write("\r\nStringed musical Instrument program");
for (int arrayIndex = 0; arrayIndex < 10; arrayIndex++) {
out.write("\r\n\r\n");
out.write("\r\nCreating new Stringed Musical Instrument object now..............");
Yournamep3 violinInstrument = new Yournamep3();
violinInstrument.setNameOfInstrument("Violin # " + (arrayIndex+1));
out.write("\r\nCreated instrument with name - "
+ violinInstrument.getNameOfInstrument());
int num = violinInstrument.getNumberOfStrings();
out.write("\r\nNumber of strings in instrument is " + num);
out.write("\r\nNames of String are ");
String strings[] = violinInstrument.getStringNames();
for (int counter = 0; counter < num; counter++) {
out.write("\r\n" + strings[counter]);
}
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nTuning now.........");
violinInstrument.setTuned(true);
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nCalling the Instrument play method now..");
violinInstrument.startPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nStopping playing of instrument..............");
violinInstrument.stopPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
}
out.close();
} catch (IOException e) {
}
}
}
I think the issue is with line 23. Any advice would be appreciated, thanks.
This is the other part of the code yournamep3
public class Yournamep3 {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public Yournamep3() {
this.isTuned = false;
this.isPlaying = false;
}
/**
* #return the name
*/
public String getNameOfInstrument() {
return name;
}
/**
* #param name the name to set
*/
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return nameofStringsInInstrument;
}
}
I would look at your getStringNames() method for your violinInstrument. It seems to me that it isn't populating your String array properly, or the getNumberOfStrings() method does not give the right number of strings. If you put the code for that up, I can help a bit more.
Line 23 appears to be
Yournamep3 violinInstrument = new Yournamep3();
If that's the case you should check the constructor for Yournamemp3
Since Line 23 is
File targetFile = new File(args [0]);
It indicates that your args object is empty. ArrayIndexOutOfBoundException is thrown to indicate that an array has been accessed with an illegal index. 0 is an illegal index.
I am trying to understand the difference between behavior of any byte oriented stream (say FileInputStream) and any Character oriented stream (say FileReader).
I went through the following: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
First program:
`import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
`
Second program:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
It says:
in CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits.
My question is: I wanted to check this above sentence so printed value of c (integer defined in program) while it was being copied. Now the value of c must be different at consecutive reads because in byte stream it reads byte by byte, so have byte value, while in character stream it reads character by character, so has character ASCII value. But it is giving same values of c. Why?
Tried to think it in different way, If my source file has only one character say 'a'.
Now CopyBytes should run while loop atleast 2 times because character takes 2 bytes. But it is running only once.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//in CopyCharacters, the int variable holds a character value in its last 16 bits;
//in CopyBytes, the int variable holds a byte value in its last 8 bits.
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("source.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
System.out.println("one");
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
Here one is printed only once
I'm trying to send data from a midlet to a servlet and recieve back a response from the servlet but I don't get any value in response. I've tried to print it on command window and it seems to be null yet I expect only two values "ok" or "error". Please help me check the code and let me know what I should do to get the response right on the midlet. My code is below:
import javax.microedition.midlet.*;//midlet class package import
import javax.microedition.lcdui.*;//package for ui and commands
import javax.microedition.io.*;//
import java.io.*;
/**
* #author k'owino
*/
//Defining the midlet class
public class MvsMidlet extends MIDlet implements CommandListener {
private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;
private Form vCode;//vote code
private StringItem welStr;
private TextField phoneField;
private StringItem phoneError;
private Command quitCmd;
private Command contCmd;
//constructor of the midlet
public MvsMidlet() {
display = Display.getDisplay(this);//creating the display object
welForm = new Form("THE MVS");//instantiating welForm object
welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
+ "Please enter the your phone number below");//instantiating welStr string item
phoneError = new StringItem("", "");//intantiating phone error string item
phoneField = new TextField("Phone number e.g 0789834141", "", 10, 3);//phone number field object
quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
welForm.append(welStr);//adding welcome string item to form
welForm.append(phoneField);//adding phone field to form
welForm.append(phoneError);//adding phone error string item to form
welForm.addCommand(contCmd);//adding continue command
welForm.addCommand(quitCmd);//adding quit command
welForm.setCommandListener(this);
display.setCurrent(welForm);
}
//start application method definition
public void startApp() {
}
//pause application method definition
public void pauseApp() {
}
//destroy application method definition
public void destroyApp(boolean unconditional) {
}
//Command action method definition
public void commandAction(Command c, Displayable d) {
if (d == welForm) {
if (c == quitCmd) {
exitMidlet();//call to exit midlet
} else {//if the command is contCmd
//place a waiting activity indicator
System.out.println("ken de man");
Thread t = new Thread() {
public void run() {
try {
//method to connect to server
sendPhone();
} catch (Exception e) {
}//end of catch
}//end of ru()
};//end of thread
t.start();//starting the thread
}//end of else
}//end of first if
}//end of command action
//defining method to exit midlet
public void exitMidlet() {
display.setCurrent(null);
destroyApp(true);
notifyDestroyed();
}//end of exitMidlet()
//defining sendPhone method
public void sendPhone() throws IOException {
System.out.println("ken de man");//check
HttpConnection http = null;//HttpConnection variable
OutputStream oStrm = null;//OutputStream variable
InputStream iStrm = null;//InputStream variable
String url = "http://localhost:8084/MvsWeb/CheckPhone";//server url
try {
http = (HttpConnection) Connector.open(url);//opening connection
System.out.println("connection made");//checking code
oStrm = http.openOutputStream();//opening output stream
http.setRequestMethod(HttpConnection.POST);//setting request type
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
byte data[] = ("phone=" + phoneField.getString()).getBytes();
oStrm.write(data);
iStrm = http.openInputStream();//openning input stream
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
int length = (int) http.getLength();
String str;
if (length != -1) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
} else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) {
bStrm.write(ch);
}
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("de man");
System.out.println(str);
if (str.equals("ok")) {
//change to vcode form
} else {
//add error message to phone_error stingItem
}
}
} catch (Exception e) {
}
}
}//end of class definition
//servlet
import java.io.*;//package for io classes
import javax.servlet.ServletException;//package for servlet exception classes
import javax.servlet.http.*;
import java.sql.*;//package for sql classes
/**
*
* #author k'owino
*/
public class CheckPhone extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//declaring variables
PrintWriter pw;//PrintWriter object
String pnum;//phone parameter sent from client
Connection con = null;//connection variable
String dbDriver = "com.jdbc.mysql.Driver";//the database driver
String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
String dbUser = "root";//database user
String dbPwd = "";//database password
PreparedStatement pstmt = null;//Prepared statement variable
String query = "select * from student where stud_phone = ?;";
ResultSet rs = null;//resultset variable
String dbPhone=null;//phone from database
//getting the "phone" parameter sent from client
pnum = req.getParameter("phone");//getting the "phone" parameter sent from client
System.out.println(pnum);
//setting the content type of the response
res.setContentType("text/html");
//creating a PrintWriter object
pw = res.getWriter();
pw.println("ken");
try{//trying to load the database driver and establish a connection to the database
Class.forName(dbDriver).newInstance();//loading the database driver
con = DriverManager.getConnection(dbUrl,dbUser,dbPwd);//establishing a connection to the database
System.out.println("connection established");
}
catch(Exception e){
}
//trying to query the database
try{
pstmt = con.prepareStatement(query);//preparing a statement
pstmt.setString(1, pnum);//setting the input parameter
rs = pstmt.executeQuery();//executing the query assigning to the resultset object
//extracring data from the resultset
while(rs.next()){
dbPhone = rs.getString("stud_phone");//getting the phone number from database
}//end of while
if(pnum.equals(dbPhone)){
pw.print("ok");
pw.close();
}
else{
pw.print("error");
pw.close();
}
}
catch(Exception e){
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}