public static void main(String[]args){
Scanner in = new Scanner(System.in);
int col=6;
int row=7;
String[][] tablero=new String[col][row];
rellenarTablero(tablero);
int grid = row*col;
for(int count=0;count<=grid;count++){
if(count%2==0){
jugador1(tablero,in);
}
else{
jugador2(tablero,in);
}
}
}
public static void jugador1(String[][] tablero,Scanner in){
int row=7;
int col1=preguntarHastaAcertar(in,"Jugador1!Que columna?");
for(row=row-1;row>=0;row--){
if(tablero[col1][row]=="."){
tablero[col1][row]="X";
break;
}
}
imprimirTablero(tablero);
}
public static void jugador2(String[][] tablero,Scanner in){
int row=7;
int col2=preguntarHastaAcertar(in,"Jugador2!Que columna?");
for(row=row-1;row>=0;row--){
if(tablero[col2][row]=="."){
tablero[col2][row]="O";
break;
}
}
imprimirTablero(tablero);
}
public static void rellenarTablero (String[][] tablero){
int col;
int row;
for(row=0;row<7;row++){
for(col=0;col<6;col++){
tablero[col][row]=".";
}
}
}
public static void imprimirTablero (String[][] tablero){
int col;
int row;
for(row=0;row<7;row++){
for(col=0;col<6;col++){
System.out.print(tablero[col][row]);
}
System.out.println(" ");
}
}
public static int preguntarHastaAcertar (Scanner in,String mensaje){
while(true){
System.out.print( mensaje );
String linea =in.nextLine();
try{
return (Integer.parseInt(linea)-1);
}
catch (NumberFormatException e){
System.out.print(linea+" no es un numero!");
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println(linea+" no es un columna correcta!");
}
}
}
How do I put a catch for ArrayIndexOutOfBoundsException e in this along with the numberFormatExcp e ?I want it too show a mesege that the column selected is not correct and keep asking me until getting the column that will actualy work.Im kinda learnind :D
An ArrayIndexOutOfBoundsException should generally not be handled as it is considered as a programming error. However, if you want to do this.. just write it the more natural way :
try {
for(row=row-1;row>=0;row--) {
if(tablero[col1][row]==".") {
tablero[col1][row]="X";
break;
}
}
} catch (ArrayIndexOutOfBoundsException ex) {
// do something
}
However, from your edited message, it would be better to do something like this :
public static int preguntarHastaAcertar (Scanner in, String mensaje, int nrows){
System.out.print(mensaje);
String linea = in.nextLine();
try {
int value = Integer.parseInt(linea) - 1;
if (value >= 0 && value < nrows)
return value;
else {
System.out.print(linea + " no es una columna correcta!");
return preguntarHastaAcertar(in,mensaje,nrows);
}
} catch (NumberFormatException e){
System.out.print(linea + " no es un numero!");
return preguntarHastaAcertar(in,mensaje,nrows);
}
}
Just tag on another catch statement..
try{
return (Integer.parseInt(linea)-1);
}
catch (NumberFormatException e){
System.out.print(linea+" is not a number!");
} catch(ArrayIndexOutOfBoundsException error){}
Related
class A {
static int a = 1 / 0;
}
In this code when we load the class, it will throw an exception because of arithmetic exception. How can I catch that exception?
use this code.
static int a=0;
try{
a = 1/0;
}catch(Exception e){
e.printStackTrace();
}
using static block
public class A {
private static int a;
static {
try {
a = 1 / 0;
} catch (Exception e) {
System.out.print("error");
}
}
}
Make it in static block.
static {
try {
Integer a = 1 / 0;
} catch (Exception e) {
}
}
Program that implements stack to check if a given string is a Palindrome or nor.
The program should accept the String from the user and check whether the string is equal to its reverse with the use of the stack operations PUSH and POP.
here's what i got so far:
import java.io.*;
import java.lang.*;
import java.util.logging.Level;
import java.util.logging.Logger;
class mystack {
DataInputStream get=new DataInputStream(System.in);
int a[];
int i,top=0,n,item,out;
void getdata()
{
try
{
//user inputs to stacks
System.out.println("Enter the limit");
n=Integer.parseInt(get.readLine());
a=new int[n];
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void push(int item)
{
if(top==n)
{
System.out.println("STACK IS FULL");
}
else
{
a[top]=item;
top++;
}
}
void pop()
{
if(top==0)
{
System.out.println("STACK EMPTY");
}
else
{
top--;
out=a[top];
}
System.out.println(out);
}
void display()
{
if(top==0){
System.out.println("STACK EMPTY");
}
else
{
for(i=top-1;i>=0;i--)
System.out.println(+a[i]);
}
}
}
class Stack
{
public static void main(String[]args)
{
DataInputStream get=new DataInputStream(System.in);
int ch = 0,t = 0;
mystack obj=new mystack();
obj.getdata();
To display stacks
System.out.println("1.PUSH 2.POP 3.DISPLAY");
try {
ch=Integer.parseInt(get.readLine());
} catch (IOException ex) {
Logger.getLogger(Stack.class.getName()).log(Level.SEVERE, null, ex);
}
while(ch!=4)
{
System.out.println("1.PUSH 2.POP 3.DISPLAY");
switch(ch)
{ enter code here
case 1:
try{
t=Integer.parseInt(get.readLine());
}
catch(IOException e)
{
}
System.out.println("value");
try {
t=Integer.parseInt(get.readLine());
obj.push(t);
} catch (IOException ex) {
Logger.getLogger(Stack.class.getName()).log(Level.SEVERE, null, ex);
}
break;
case 2:
obj.pop();
break;
case 3:obj.display();
break;
}
}
}
}
I can't figure out how to create palindrome and i can't output my stacks
This should be in comments but don't have enough reputation.Check this Question Check if given string is a palindrome using stack
how can I search a data using binary search? When if statement begins, the program goes to IOException block. It seems that it doesn't try to read the file.
public void busquedaDicotomica1(String clave)
{
String lectura1=null, lectura2=null ;
long posicion;
long tamaño;
long midValue;
boolean valido = true;
try
{
rafObj = new RandomAccessFile("indice1.ind","r");
tamaño = rafObj.length();
midValue = tamaño/2;
rafObj.seek(midValue);
if(clave.equalsIgnoreCase(rafObj.readUTF()))
{
System.out.println("ok");
}
else
{
System.out.println("no");
}
}
catch(EOFException eoe)
{}
catch(FileNotFoundException nfe)
{
VentanaPrincipal.setErrorText(dialogo);
}
catch(IOException ioe)
{
VentanaPrincipal.setErrorText(ioe.getMessage());
}
}
}
I have these two Class :
public class TryException {
int a=0;
TryException(int c) {
a = c;
}
public boolean operation() //just example
{
if(a!=10)
{
System.out.println(a);
return true;
}else{
throw new RuntimeException("display something");
}
}
}
and the main :
public class Test {
static public void main(String args[])
{
int val =20;
TryException ex = new TryException(val);
try{
while(ex.operation()){
ex.a = --val;
}
}catch(RuntimeException e)
{
System.out.println("try exception");
}
}
}
when i run this program, the execution is stoped just when it detects the exception. How to continue the execution of the same while after exception ?
Move the try-catch inside the loop.
boolean run = true;
while(run){
ex.a = --val;
try{
run = ex.operation();
}catch(RuntimeException e){
System.out.println("try exception");
}
}
You need to decide when to set run to false...
It may help...
public class Test {
static public void main(String args[])
{
int val =20;
TryException ex = new TryException(val);
boolean status = true;
while(status){
try{
status = ex.operation();
} catch(RuntimeException e) {
status = true; //Or whatever...
}
ex.a = --val;
}
}
}
1.Problem on emulator:
I am launching my midlet app at first time is to store some data and then I am restarting it at second time is to read the stored data. It is working well in first two cases without any exception.
However I am restarting it second time on the same way then It gives exception: "Uncaught exception java/lang/NumberFormatException:" it is processing only char and total data is less than 64 kb.
2.Problem on real device:
RMS is not working at all. I don't know if I need to give a permission for the handset (nokia n95).
Thanks.
In app, it is only storing charity companies into rms according to a selected country. So if a country is already selected, it must skip country list and then display company list in every restart.
In below code, rms_Check() method is to check the data in order to open country or company list frame.
public class X {
private static RecordStore rs =null;
private static Vector rms_Vector = new Vector();
static final String REC_STORE ="db_1";
public X() {
}
public void openRecStore(){
try {
rs = RecordStore.openRecordStore(REC_STORE, true);
System.out.println("open record store");
} catch (Exception e)
{
db(e.toString()+" in openRecStore");
}
}
public void closeRecStore(){
try {
rs.closeRecordStore();
} catch (Exception e) {
db(e.toString()+" in closeRecStore");
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores()!=null){
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString()+" in deleteRecStore");
}
}
}
public void writeRecord(String str) throws UnsupportedEncodingException
{
byte[] rec = str.getBytes("UTF-8");
try {
rs.addRecord(rec, 0, rec.length);
System.out.println("write record store");
} catch (Exception e) {
db(e.toString()+" in writeRecord");
}
}
public void readRecord()
{
try {
// Intentionally it is too small to test code
byte[] m_enc = new byte[5];
byte[] recData = new String(m_enc).getBytes("UTF-8");
int len;
for(int i =1; i<= rs.getNumRecords(); i++){
if(rs.getRecordSize(i)> recData.length)
recData = new byte[rs.getRecordSize(i)];
len = rs.getRecord(i, recData, 0);
System.out.println("Record #"+i+":"+new String(recData, 0, len));
System.out.println("------------------------");
rms_Vector.addElement(new String(recData, 0, len));
}
} catch (Exception e) {
db(e.toString() +" in readStore");
}
}
private void db(String str)
{
System.out.println("Msg:"+str);
}
public Vector rms_Array(){
return this.rms_Vector;
}
public boolean rms_Check(){
if(this.rms_Vector.size()>0){
System.out.print("rms_check: true");
// if true it will display company list every time
return true;
}else{
System.out.print("rms_check: false");
//if false it will display country list then company list
return false;
}
}
}
Use this
private RecordStore rs = null; // Record store
public String REC_STORE = "RSM name"; // Name of record store
public int record_max=0;
public void openRecStore(){
try{
rs = RecordStore.openRecordStore(REC_STORE, true );
}catch (Exception e){}
}
public void closeRecStore(){
try{
rs.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(REC_STORE);
}catch (Exception e){}
}
}
public void writeRecord(String str){
byte[] rec = str.getBytes();
try{
rs.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void readRecords(){
try{
byte[] recData = new byte[5];
int len;
record_max=rs.getNumRecords();
for(int i = 1; i <= record_max; i++){
if(rs.getRecordSize(i) > recData.length){
recData = new byte[rs.getRecordSize(i)];
}
len = rs.getRecord(i, recData, 0);
file_name[i]=new String(recData, 0, len);
}
}catch (Exception e){}
}
you have file_name[] array of save data
for load actin commad use :
openRecStore();
readRecords();
for(int j=1;j<=record_max;j++ ) {
System.out.println("Record " + j + " : " + file_name[j]);
}
closeRecStore();
and save this :
openRecStore();
writeRecord(textField.getString());
closeRecStore();