i've got a problem when i use try-catch in the search method. when i input the wrong data, it just skips the catch block and output the code below it
do {
System.out.print(menu[1]);
jumlah = sc1.nextInt();
System.out.print(menu[0]);
tujuan = sc1.nextInt();
for (int i = 0; i < DataRek.length; i++) {
try {
if (tujuan == DataRek[i]) {
index = i;
nasabah = NamaRek[index];
break;
}
} catch (InputMismatchException e) {
System.out.println("DATA NASABAH TIDAK DITEMUKAN, SILAHKAN COBA LAGI");
System.exit(0);
}
}
} while (loop2 == 1);
System.out.println("Nomor rekening tujuan: " + tujuan);
System.out.println("Nama Nasabah: " + nasabah);
System.out.println("Jumlah yang ditransfer: " + jumlah);
System.out.println("Apakah data diatas sudah benar? (Y/N) ");
loop1 = sc1.next().charAt(0);
when i input the wrong data, i expect the output of DATA NASABAH TIDAK DITEMUKAN, but the actual output is the code below it.
The InputMismatchException is potentially thrown by Scanner's methods. You need to include them in the try block:
do {
try {
System.out.print(menu[1]);
jumlah = sc1.nextInt();
System.out.print(menu[0]);
tujuan = sc1.nextInt();
for (int i = 0; i < DataRek.length; i++) {
if (tujuan == DataRek[i]) {
index = i;
nasabah = NamaRek[index];
break;
}
}
} catch (InputMismatchException e) {
System.out.println("DATA NASABAH TIDAK DITEMUKAN, SILAHKAN COBA LAGI");
System.exit(0);
}
} while (loop2 == 1);
Related
I have a jTextField, jLabel and a jButton. I want to set the jTextField to empty and update the jLabel to some new text after I perform jButton action.
This my code for jButtonActionPerformed(ActionEvent e) method:
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedWriter fw;
StringBuilder guessword = new StringBuilder(word);
try {
fw = new BufferedWriter(new FileWriter("C:\\Users\\Arihant\\JavaApplication1\\src\\javaapplication1\\scores.txt", true));
while(guesses != 0) {
jLabel26.setText(Integer.toString(guesses));
guesschar = jTextField2.getText().charAt(0);
flag = 0;
for(int j = 0; j < word.length() / 2; j++) {
if(Character.toLowerCase(guesschar) == temp[j] && (guessword.toString().indexOf(Character.toLowerCase(guesschar)) < 0)) {
flag = 1;
for(int k = 0; k < word.length(); k++) {
if(Character.toLowerCase(guesschar) == word.charAt(k))
guessword.setCharAt(k, Character.toLowerCase(guesschar));
}
if(guessword.toString().equals(word)) {
switch (difficulty) {
case "EASY":
points = guesses * 50;
break;
case "MODERATE":
points = guesses * 100;
break;
case "HARD":
points = guesses * 200;
break;
default:
points = 0;
break;
}
try {
fw.append(name + " " + points);
fw.newLine();
fw.close();
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
jPanel13.removeAll();
jPanel13.add(jPanel4);
jPanel13.repaint();
jPanel13.revalidate();
jLabel29.setText("<html>YOU WIN!<br/> The word was: </html>" + word);
jLabel31.setText("You scored: " + points + " points.");
jLabel28.setText("Play again?");
}
}
}
if(flag == 0) {
guesses--;
}
jPanel13.repaint();
jPanel13.revalidate();
jLabel1.setText(guessword.toString());
jTextField2.setText("");
Document document = jTextField2.getDocument();
document.addDocumentListener(new JButtonStateController(jButton8, 0));
((AbstractDocument) jTextField2.getDocument()).setDocumentFilter(new JTextFieldFilter(0));
}
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
When I click jButton8, it just skips the entire code in try-catch block and goes directly to jPanel13.removeAll();.
I want to set the jTextField2 to empty and jButton8 to disabled, each time I click jButton8.
Tell me, where I am wrong and how can I improve my code?
I created a chat in Java, which displays the messages sent and received on the screen. The problem is that when sending the message it is picking up the previously sent value. For example, I send the message written "Microsoft", and then I send another message written "Apple", when the display shows "Applesoft", it appears that it is not emptying DatagramPacket. What can be done?
class Recebe implements Runnable {
#Override
public void run() {
byte[] dadosReceber = new byte[255];
boolean erro = false;
DatagramSocket socket = null;
while (true) {
try {
socket = new DatagramSocket(getPorta());
} catch (SocketException ex) {
Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
}
erro = false;
while (!erro) {
DatagramPacket pacoteRecebido = new DatagramPacket(dadosReceber, dadosReceber.length);
try {
socket.receive(pacoteRecebido);
byte[] b = pacoteRecebido.getData();
String s = "";
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
s += (char) b[i];
System.out.println("Valor S: " + s + " ");
}
}
// if (!s.equals(new GeraHash().MD5("envie a chave publica!!!"))) {
String nome = pacoteRecebido.getAddress().toString() + " disse:";
notifica(nome + s);
System.out.println("Dados Recebe 2: " + s + " ");
// } else {
// conexaoAtual().envia("Funcionou!");
// System.out.println("Dados Recebe 1: " + s + " ");
// }
} catch (Exception e) {
System.out.println("erro");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
}
erro = true;
continue;
}
}
}
}
}
socket.receive(pacoteRecebido);
byte[] b = pacoteRecebido.getData();
String s = "";
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
s += (char) b[i];
System.out.println("Valor S: " + s + " ");
}
Usual problem. You're ignoring the actual length of the received datagram, given by DatagramPacket.getLength(). You can reduce all that to:
socket.receive(pacoteRecebido);
System.out.println(new String(pacoteRecebido.getData(), 0, pacoteRecebido.getLength());
So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
I am working on an inventory program and keep running into an issue. I have some text files that are named using a combination of numbers. I call them shelves. I open them up and edit them to store items in them. I am having a problem after I remove some objects from one of these.
How that process goes is I will open the file. Load it into a JTable. Select the item and amount I wish to remove. Then re save the file. That all works great until I go to open another shelf. Any other shelf I try to open after that process tells me that the shelf does not exist even if it the same one I just used. I can still go through the path on my computer and find it just fine and I can close the program and reopen it and it works just fine again until I remove and item from the shelf. I will post any relevant code below. Thanks for the help guys.
String[] binCombos = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
JComboBox<String> aisle, column, row;
JButton open = new JButton("Open Shelf");
tableHolder = new JScrollPane(shelfsContents);
aisle = new JComboBox<String>(binCombos);
column = new JComboBox<String>(binCombos);
row = new JComboBox<String>(binCombos);
open.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
shelfCombo = aisle.getSelectedItem().toString() + column.getSelectedItem().toString() + row.getSelectedItem().toString() + ".txt";
File shelfName = new File(sPath + "\\" + shelfCombo);
if(shelfName.exists() == true && Console.console.IsPulling() == false)
{
OpenShelf(shelfName);
}
else
{
System.out.println(shelfName + " does not exist");
}
}
});
private void SaveShelf()
{
try
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
bfw.write(tableModel.getValueAt(i, j).toString());
bfw.write(" : ");
}
}
}
bfw.newLine();
}
bfw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try this code
private void SaveShelf(){
PrintWriter pw ;
try
{
pw = new PrintWriter(new File("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
pw.print(tableModel.getValueAt(i, j).toString());
pw.print(" : ");
}
}
}
pw.println();
pw.flush();
}
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
pw.close();
}
}