Two Dimensional Arrays, Exception in thread "main" java.util.InputMismatchException - java

I have a little question. I need to read two words in a line for put name and lastname.
public void Promedios5(){
Scanner Marbis=new Scanner(System.in);
String[] x=new String[5];
double[][] a=new double[5][4];
double[] b=new double [5],c=new double[5];
System.out.println("Este programa genera los promedios de las notas de cuatro unidades\n"
+ "se le solicitarán a usted, el nombre y las cuatro notas");
System.out.println("Podría ingresarlas ahora por favor:");
for(int y=0;y<=4;y++){
System.out.println("Ingrese el nombre:");
x[y]=Marbis.nextLine();
for(int z=0;z<=3;z++){
a[y][z]=Marbis.nextDouble();
}
b[y]=a[y][0]+a[y][1]+a[y][2]+a[y][3];
c[y]=b[y]/4;
}
System.out.println("Ahora usted verá los promedios de las personas:");
System.out.println("Nombre:\t\t\tPromedio");
for(int m=0;m<=4;m++)
System.out.printf("%s:\t\t%.2f\n",x[m],c[m]);
}
Here I have the error: x[y]=Marbis.nextLine();
I know that I use it for two or more words in a Line, but in the second chances it marks me error, like this (This is the result, I think that I can use arrays in nextLine):
MArio Albert
100
100.00
78.00
100.00
Ingrese el nombre:
John Antoinie
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at vectormarbis1.MarbisVectors2.Promedios5(MarbisVectors2.java:125)
at vectormarbis1.VectorMarbis1.main(VectorMarbis1.java:28)
C:\Users\ManoloAurelio\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 39 seconds)

You only flush the output in Java.
When to discard the rest of the line? To solve your problem you can call
input.nextLine();
You need to do this after nextDouble() as you expect to be reading from the next line.
I hope the below given code helps you solve your problem.
public void Promedios5(){
Scanner Marbis=new Scanner(System.in);
String[] x=new String[5];
double[][] a=new double[5][4];
double[] b=new double [5],c=new double[5];
System.out.println("Este programa genera los promedios de las notas de cuatro unidades\n"
+ "se le solicitarán a usted, el nombre y las cuatro notas");
System.out.println("Podría ingresarlas ahora por favor:");
for(int y=0;y<=4;y++){
System.out.println("Ingrese el nombre:");
x[y]=Marbis.nextLine();
for(int z=0;z<=3;z++){
a[y][z]=Marbis.nextDouble();
}
Marbis.nextLine(); //Just add this line here
b[y]=a[y][0]+a[y][1]+a[y][2]+a[y][3];
c[y]=b[y]/4;
}
System.out.println("Ahora usted verá los promedios de las personas:");
System.out.println("Nombre:\t\t\tPromedio");
for(int m=0;m<=4;m++)
System.out.printf("%s:\t\t%.2f\n",x[m],c[m]);
}

Related

HashSet Remove false

Hello Im trying to remove an elemento from a HashSet that have an entity created by me that is called "Product" this is the code:
Set listaItemsTrans = this.getTransaction().getTransactionItems();
HashSet listaIteratorI = new HashSet();
listaIteratorI.addAll(listaItemsTrans);
Iterator itemSet = listaIteratorI.iterator();
while (itemSet.hasNext())
{
Product prodBif = (Product) itemSet.next();
logger.debug("Prod bif = " + prodBif.getIdProduct() + " = " + "Prod search = " + prodSearch.getIdProduct());
if (prodBif.getIdProduct().compareTo(prodSearch.getIdProduct()) == 0)
{
logger.debug("El Producto ha sido encontrado");
try
{
logger.debug("ProdBif " + prodBif);
logger.debug("Lista de productos 3 " + this.getTransaction().getTransactionItems());
boolean isRemoved;
isRemoved = this.getTransaction().getTransactionItems().remove(prodBif);
logger.debug("isRemoved? " + isRemoved);
}
catch (Exception e)
{
e.printStackTrace();
}
logger.debug("Lista de productos 4" + this.getTransaction().getTransactionItems());
prodBif = prodSearch;
this.getTransaction().getTransactionItems().add(prodBif);
logger.debug("Lista de productos 5" + this.getTransaction().getTransactionItems());
isOkey = true;
}
}
The product is the same i already check that but im gonna put the product equal:
Product Bif: Product [idProduct=1546405266442777, transaction=Transaction [idTransaction=1546405253162777, transaction=077700514, transactionDate=2019-01-02 10:01:06, session=Session [idSession=1546405226194777, session=00130777000000011111, cashier=com.lds.exito.darchitecture.domainmodel.entities.Cashier#d8241df3, store=Store [idStore=1546405226193777, store=0013, description=EXTITO GRAN VIA M001120], terminal=777, sessionDate=2019-01-02 10:00:26], sequenceNumber=0514, ], pluVariety=000000213690, salePrice=9900, description=NEVERA NO FROST 39, details={CashierID=0000011111, mensaje=Certificado valido, TransactionID=0514, AuthorizationBus=CommunicationHttpBodyAuthBus, ValidationResponseRevertionStatus=com.lds.exito.soa.status.validation.IvaDifResponseStatusValidation, portPrimary=, hostPrimary=http://wsredverde.datagestion.co/ws/?a=2&certificado=3&identificacion=8276946&codigo=13, contentType=application/json, StoreID=0013, PREFIX_AUTH_END_identificacion==8276946, OriginalTerminalID=777, nroIdentificacion=8276946, uri=, AuthorizationClassName=FinalAuthorizationHttp, plu=000000213690, PREFIX_AUTH_END_certificado==3, TerminalID=777, fechaHora=2019-01-02T10:01:06, nroCertificado=3, OriginalTransactionID=0514}, extras={transaction_record=IvaDif/IvaDif-99-129,,, voucher_list=IvaDif/FooterRecarga,}, authorizationType=ParametersConfig [idParameter=2, descriptionGroup=Tipos de Autorizacion, idGroup=TPAUT, descriptionParameter=Autorizacion al Final de la Transaccion, parameterValue=ENDTR], authorizationStatus=ParametersConfig [idParameter=3, descriptionGroup=Estado de la Autorizacion, idGroup=STAUT, descriptionParameter=Pendiente, parameterValue=PNDNG], reverseType=ParametersConfig [idParameter=7, descriptionGroup=Tipos de Reverso, idGroup=TPREV, descriptionParameter=No Aplica, parameterValue=NOAPP], reverseStatus=ParametersConfig [idParameter=8, descriptionGroup=Estado del Reverso, idGroup=STREV, descriptionParameter=No Aplica, parameterValue=NOAPP], anulationType=ParametersConfig [idParameter=11, descriptionGroup=Tipos de Anulacion, idGroup=TPANU, descriptionParameter=Aplica, parameterValue=APPLY], anulationStatus=ParametersConfig [idParameter=13, descriptionGroup=Estado del Anulacion, idGroup=STANU, descriptionParameter=No Aplica, parameterValue=NOAPP], productType=ParametersConfig [idParameter=16, descriptionGroup=Tipos de Producto, idGroup=TPPDT, descriptionParameter=Item, parameterValue=ITEM], quantity=1, ]
Product in the HashSet: Product [idProduct=1546405266442777, transaction=Transaction [idTransaction=1546405253162777, transaction=077700514, transactionDate=2019-01-02 10:01:06, session=Session [idSession=1546405226194777, session=00130777000000011111, cashier=com.lds.exito.darchitecture.domainmodel.entities.Cashier#d8241df3, store=Store [idStore=1546405226193777, store=0013, description=EXTITO GRAN VIA M001120], terminal=777, sessionDate=2019-01-02 10:00:26], sequenceNumber=0514, ], pluVariety=000000213690, salePrice=9900, description=NEVERA NO FROST 39, details={CashierID=0000011111, mensaje=Certificado valido, TransactionID=0514, AuthorizationBus=CommunicationHttpBodyAuthBus, ValidationResponseRevertionStatus=com.lds.exito.soa.status.validation.IvaDifResponseStatusValidation, portPrimary=, hostPrimary=http://wsredverde.datagestion.co/ws/?a=2&certificado=3&identificacion=8276946&codigo=13, contentType=application/json, StoreID=0013, PREFIX_AUTH_END_identificacion==8276946, OriginalTerminalID=777, nroIdentificacion=8276946, uri=, AuthorizationClassName=FinalAuthorizationHttp, plu=000000213690, PREFIX_AUTH_END_certificado==3, TerminalID=777, fechaHora=2019-01-02T10:01:06, nroCertificado=3, OriginalTransactionID=0514}, extras={transaction_record=IvaDif/IvaDif-99-129,,, voucher_list=IvaDif/FooterRecarga,}, authorizationType=ParametersConfig [idParameter=2, descriptionGroup=Tipos de Autorizacion, idGroup=TPAUT, descriptionParameter=Autorizacion al Final de la Transaccion, parameterValue=ENDTR], authorizationStatus=ParametersConfig [idParameter=3, descriptionGroup=Estado de la Autorizacion, idGroup=STAUT, descriptionParameter=Pendiente, parameterValue=PNDNG], reverseType=ParametersConfig [idParameter=7, descriptionGroup=Tipos de Reverso, idGroup=TPREV, descriptionParameter=No Aplica, parameterValue=NOAPP], reverseStatus=ParametersConfig [idParameter=8, descriptionGroup=Estado del Reverso, idGroup=STREV, descriptionParameter=No Aplica, parameterValue=NOAPP], anulationType=ParametersConfig [idParameter=11, descriptionGroup=Tipos de Anulacion, idGroup=TPANU, descriptionParameter=Aplica, parameterValue=APPLY], anulationStatus=ParametersConfig [idParameter=13, descriptionGroup=Estado del Anulacion, idGroup=STANU, descriptionParameter=No Aplica, parameterValue=NOAPP], productType=ParametersConfig [idParameter=16, descriptionGroup=Tipos de Producto, idGroup=TPPDT, descriptionParameter=Item, parameterValue=ITEM], quantity=1, ]
And i dont know why that is happening, something that i miss?
Note 1: when i try to do the same thing with another product that code works
Note 2: Im using java 1.4 by restrictions in the hardware

Java scanner.nextDouble()

Hi I am just learning java with a book; in this, there is an excersise called loan; I am following the sample, but when I want to test the program after I type the loan amount named by me as montoPrestamo (in Spanish) but when I type any value, netBeans does not nothing, no error, no exception, no next prompt, nothing.
I dont know what is going on or where is the mistake.
thanks
here is my code:
public static void main(String[] args) {
double montoPrestamo, interesAnual,pagoMensual,pagoTotal;
int tiempoPrestamo;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator"));
System.out.print("Monto del prestamo (Pesos y Centavos): ");
montoPrestamo = scanner.nextDouble();
System.out.print("el valor ingresado es " + montoPrestamo);
System.out.print("Tasa de Interes anual (ejemplo, 9,5): ");
interesAnual=scanner.nextDouble();
System.out.print("Tiempo de periodo del prestamo en años : ");
tiempoPrestamo=scanner.nextInt();
System.out.println("");
System.out.println("Cantidad solicitada $"+montoPrestamo);
System.out.println("la tasa de interes de su prestamo:"+interesAnual+"%");
System.out.println("Tiempo del prestamo en años"+tiempoPrestamo);
System.out.println("\n");
System.out.println("Pago mensual"+pagoMensual);
System.out.println("Pago total"+pagoTotal);
}
It works after removing this line:
scanner.useDelimiter(System.getProperty("line.separator"));
Probably this does not work from within an IDE because it uses an own terminal which might use another linefeed separator than your operating system.

Execution stops after the instantiation of a variable with a scanner input

I'm doing internships with a small project that asks the user to select a category of expenses, to later request quantities that are stored in a ArrayList and finally the amount of the total expenses of that category is printed on the screen. The problem comes at the moment in which I associate the variable 'quantity' with a Scanner entry, at that moment the execution thread remains in Execution and it does not return any type of error.
package gestioneconomica;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
/**
*
* #author Robin
*/
class Gastos {
//Declaración de los tipos de gastos organizados en ArrayList()
ArrayList<Double> taberna=new ArrayList<>();
ArrayList<Double> tPublico=new ArrayList<>();
ArrayList<Double> alimentacion=new ArrayList<>();
ArrayList<Double> formacion=new ArrayList<>();
//Declaración e inicialización de la suma de los valores de cada ArrayList()
double sumTaberna=0.0;
double sumTPublico=0.0;
double sumAlimentacion=0.0;
double sumFormacion=0.0;
//Instanciación del objeto 'sc' de la clase Scanner
Scanner sd=new Scanner(System.in);
//*************THE NEXT LINE CAUSES THE ERROR****************
double quantity=sd.nextDouble();
//Declaración e inicialización de métodos
public void addTaberna(){
System.out.print("Ingrese importe: ");
while(quantity!=0){
taberna.add(quantity);
}
System.out.print("El total consumido en esta categoría es de: ");
Iterator <Double> itTaberna=taberna.iterator();
while(itTaberna.hasNext()){
System.out.println(itTaberna.next());
}
}
public void addtPublico(){
System.out.print("Ingrese importe: ");
while(quantity!=0){
tPublico.add(quantity);
}
Iterator <Double> itTPublico=tPublico.iterator();
while(itTPublico.hasNext()){
sumTPublico+=itTPublico.next();
}
System.out.println("Gastos totales en Transporte Público: " + sumTPublico);
}
public void addAlimentacion(){
System.out.print("Ingrese importe: ");
alimentacion.add(sd.nextDouble());
}
public void addFormacion(){
System.out.print("Ingrese importe: ");
formacion.add(sd.nextDouble());
}
}
//THIS IS THE DRIVER CLASS
package gestioneconomica;
import java.util.Scanner;
class GastosExe{
public static void main(String[]args){
System.out.println("###################################################");
System.out.println("BIENVENIDO/A AL PROGRAMA DE GASTOS DE ROBIN");
System.out.println("###################################################");
System.out.println("(1)TABERNA\t(2)TRANSPORTE PÚBLICO\t(3)ALIMENTACIÓN\t (4)INVERSIÓN FORMATIVA");
System.out.println("Seleccione el tipo de Gasto: ");
Gastos gastos=new Gastos();
Scanner sc=new Scanner(System.in);
int tipo=sc.nextInt();
switch(tipo){
case 1:
System.out.println("Ha seleccionado Taberna");
gastos.addTaberna();
break;
case 2:
System.out.println("Ha seleccionado Transporte Público");
break;
case 3:
System.out.println("Ha seleccionado Alimentación");
gastos.addAlimentacion();
break;
case 4:
System.out.println("Ha seleccionado Inversión Formativa");
gastos.addFormacion();
break;
}
}
}
Welcome to SO. This is a very nicely phrased first question.
at that moment the execution thread remains in Execution and it does
not return any type of error
That's because there is no error here. And the correct term is "at the moment the execution thread (main thread) remains blocked" Your program is behaving exactly the way you coded it to behave
Let's break it down from the main method.
Gastos gastos=new Gastos();
When you call the Gastos constructor here on the main method, the Gastos class initializes, which has the quantity field of type double, initialized directly with the input from the Scanner.
When execution reaches this line double quantity = sd.nextDouble(); it blocks the main thread, waiting for keyboard input from the user..
So you should enter a selection here 1
when you press enter, sd.nextDouble(); method returns, and main thread resumes.
Then, when the Gastos() constructor call returns and the main thread reaches this line int tipo = sc.nextInt();
Which blocks the main thread again, waiting for another keyboard input from the user.
So you should enter a selection here again 2
When you press enter, sc.nextInt(); method returns and the main thread resumes execution
Sample run
###################################################
BIENVENIDO/A AL PROGRAMA DE GASTOS DE ROBIN
###################################################
(1)TABERNA (2)TRANSPORTE PÚBLICO (3)ALIMENTACIÓN (4)INVERSIÓN FORMATIVA
Seleccione el tipo de Gasto:
1
2
Ha seleccionado Transporte Público
try:
double quantity = Double.parseDouble(sd.nextLine());

java.util.regex.PatternSyntaxException Android

I am replacing part of a string as follows
biblebook.replaceAll("[{\"-bnumber\":\"1\",\"-bname\":\"Genesis\",\"CHAPTER\":","[");
but my log shows the following error
09-25 16:33:47.421: W/System.err(5116): java.util.regex.PatternSyntaxException: Missing closing bracket in character class near index 46:
09-25 16:33:47.421: W/System.err(5116): [{"-bnumber":"1","-bname":"Genesis","CHAPTER":
09-25 16:33:47.421: W/System.err(5116): ^
09-25 16:33:47.421: W/System.err(5116): at java.util.regex.Pattern.compileImpl(Native Method)
09-25 16:33:47.421: W/System.err(5116): at java.util.regex.Pattern.compile(Pattern.java:400)
09-25 16:33:47.429: W/System.err(5116): at java.util.regex.Pattern.<init>(Pattern.java:383)
09-25 16:33:47.429: W/System.err(5116): at java.util.regex.Pattern.compile(Pattern.java:374)
09-25 16:33:47.429: W/System.err(5116): at java.lang.String.replaceAll(String.java:1784)
09-25 16:33:47.429: W/System.err(5116): at .Index$loadingTask.doInBackground(Index.java:383)
any idea ?
UPDATE this is part of my string
[{"-bnumber":"1","-bname":"Genesis","CHAPTER":[{"-cnumber":"1","VERS":[{"-vnumber":"1","#text":"Au
commencement, Dieu créa les cieux et la
terre."},{"-vnumber":"2","#text":"La terre était informe et vide: il y
avait des ténèbres à la surface de l'abîme, et l'esprit de Dieu se
mouvait au-dessus des eaux."},{"-vnumber":"3","#text":"Dieu dit: Que
la lumière soit! Et la lumière fut."},{"-vnumber":"4","#text":"Dieu
vit que la lumière était bonne; et Dieu sépara la lumière d'avec les
ténèbres."},{"-vnumber":"5","#text":"Dieu appela la lumière jour, et
il appela les ténèbres nuit. Ainsi, il y eut un soir, et il y eut un
matin: ce fut le premier jour."},{"-vnumber":"6","#text":"Dieu dit:
Qu'il y ait une étendue entre les eaux, et qu'elle sépare les eaux
d'avec les eaux."},{"-vnumber":"7","#text":"Et Dieu fit l'étendue, et
il sépara les eaux qui sont au-dessous de l'étendue d'avec les eaux
qui sont au-dessus de l'étendue. Et cela fut
ainsi."},{"-vnumber":"8","#text":"Dieu appela l'étendue ciel. Ainsi,
il y eut un soir, et il y eut un matin: ce fut le second
jour."},{"-vnumber":"9","#text":"Dieu dit: Que les eaux qui sont
au-dessous du ciel se rassemblent en un seul lieu, et que le sec
paraisse. Et cela fut ainsi."},{"-vnumber":"10","#text":"Dieu appela
le sec terre, et il appela l'amas des eaux mers. Dieu vit que cela
était bon."},{"-vnumber":"11","#text":"Puis Dieu dit: Que la terre
produise de la verdure, de l'herbe portant de la semence, des arbres
fruitiers donnant du fruit selon leur espèce et ayant en eux leur
semence sur la terre. Et cela fut
ainsi."},{"-vnumber":"12","#text":"La terre produisit de la verdure,
de l'herbe portant de la semence selon son espèce, et des arbres
donnant du fruit et ayant en eux leur semence selon leur espèce. Dieu
vit que cela était bon."},{"-vnumber":"13","#text":"Ainsi, il y eut un
soir, et il y eut un matin: ce fut le troisième
jour."},{"-vnumber":"14","#text":"Dieu dit: Qu'il y ait des luminaires
dans l'étendue du ciel, pour séparer le jour d'avec la nuit; que ce
soient des signes pour marquer les époques, les jours et les
années;"},{"-vnumber":"15","#text":"et qu'ils servent de luminaires
dans l'étendue du ciel, pour éclairer la terre. Et cela fut
ainsi."},{"-vnumber":"16","#text":"Dieu fit les deux grands
luminaires, le plus grand luminaire pour présider au jour, et le plus
petit luminaire pour présider à la nuit; il fit aussi les
étoiles."},{"-vnumber":"17","#text":"Dieu les plaça dans l'étendue du
ciel, pour éclairer la terre,"},{"-vnumber":"18","#text":"pour
présider au jour et à la nuit, et pour séparer la lumière d'avec les
ténèbres. Dieu vit que cela était
bon."},{"-vnumber":"19","#text":"Ainsi, il y eut un soir, et il y eut
un matin: ce fut le quatrième jour."},{"-vnumber":"20","#text":"Dieu
dit: Que les eaux produisent en abondance des animaux vivants, et que
des oiseaux volent sur la terre vers l'étendue du
ciel."},{"-vnumber":"21","#text":"Dieu créa les grands poissons et
tous les animaux vivants qui se meuvent, et que les eaux produisirent
en abondance selon leur espèce; il créa aussi tout oiseau ailé selon
son espèce. Dieu vit que cela était
bon."},{"-vnumber":"22","#text":"Dieu les bénit, en disant: Soyez
féconds, multipliez, et remplissez les eaux des mers; et que les
oiseaux multiplient sur la terre."},{"-vnumber":"23","#text":"Ainsi,
il y eut un soir, et il y eut un matin: ce fut le cinquième
jour."},{"-vnumber":"24","#text":"Dieu dit: Que la terre produise des
animaux vivants selon leur espèce, du bétail, des reptiles et des
animaux terrestres, selon leur espèce. Et cela fut
ainsi."},{"-vnumber":"25","#text":"Dieu fit les animaux de la terre
selon leur espèce, le bétail selon son espèce, et tous les reptiles de
la terre selon leur espèce. Dieu vit que cela était
bon."},{"-vnumber":"26","#text":"Puis Dieu dit: Faisons l'homme à
notre image, selon notre ressemblance, et qu'il domine sur les
poissons de la mer, sur les oiseaux du ciel, sur le bétail, sur toute
You have to escape the square brackets ([ and ]) using double backslash (\\), as they have a function in regexp... (edit: and of course the curly brackets too { })
biblebook.replaceAll("\\[\\{\"-bnumber\":\"1\",\"-bname\":\"Genesis\",\"CHAPTER\":","\\[");
Also: I find it helps me to use an online regex checker like this as it makes work much quicker
If you want to replace that exact string and don't want to use a regex, use biblebook.replace() instead of biblebook.replaceAll().
If you want to include [ as a part of your regex expression, then you need to close the bracket.
[{\"-bnumber\":\"1\",\"-bname\":\"Genesis\",\"CHAPTER\]
But if the bracket [ is part of your string, then you need to escape as
\\[{\"-bnumber\":\"1\",\"-bname\":\"Genesis\",\"CHAPTER\

I would like to change this code to display only "OK" and delete the cancel button

I would like to change this code to display only "OK" and delete the cancel button.
Object contestacion5 = JOptionPane.showInputDialog(null, "#5 Que describe mejor a la Norteña?", "Examen Tijuanas PR", //3
JOptionPane.DEFAULT_OPTION, null,
new Object[] {"Ensalada de espinacas, tomates, zetas, cebolla, tocineta, aguacate, queso de hoja y tiras de maiz crujientes en vinagreta de la casa.",
"Lechuga romana servida con tomate, cebolla, maiz, aguacate, queso de hoja y tiritas de maiz crujientes acompañado de su seleccion de filetes de pollo de res.",
"Ensalada vegetariana de nopales, tomates, cebolla, lechuga romana, queso de hoja, aguacate, y aderezo especial de la casa." }, null);
Here it is the picture, I want it exactly as this but without the Cancel button, thanks!
I did some experimenting. It's easy enough to use showInputDialog to show the answers in a dropdown list (combobox) but it does not seem to be possible to remove the Cancel button.
Instead you can use showConfirmDialog, where the 'message' is not a simple String, but a visual panel containing: (1) a label for the question; (2) a combobox for the answers. I've wrapped this up into a method to make it easier to use:
static int showQuestion(String dialogTitle, String question, String[] answers) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(question), BorderLayout.NORTH);
JComboBox<String> comboBox = new JComboBox<>(answers);
panel.add(comboBox);
if (JOptionPane.CLOSED_OPTION == JOptionPane.showConfirmDialog(null, panel, dialogTitle, JOptionPane.DEFAULT_OPTION)) {
return -1;
}
return comboBox.getSelectedIndex();
}
Example usage:
int choice = showQuestion("Examen Tijuanas PR", "#5 Que describe mejor a la Norteña?", new String[] {
"Ensalada de espinacas, tomates, zetas, cebolla, tocineta, aguacate, queso de hoja y tiras de maiz crujientes en vinagreta de la casa.",
"Lechuga romana servida con tomate, cebolla, maiz, aguacate, queso de hoja y tiritas de maiz crujientes acompañado de su seleccion de filetes de pollo de res.",
"Ensalada vegetariana de nopales, tomates, cebolla, lechuga romana, queso de hoja, aguacate, y aderezo especial de la casa.",
});
System.out.println("User chose #" + choice);
The showQuestion method returns the 0-based index of the answer the user chose. The dialog has an 'OK' button but no 'Cancel' button; however, there's still a problem: the user can still close the dialog by clicking the 'X' of the dialog, or by right-clicking the titlebar and selecting 'Close' from the popup menu. That has the same effect as 'Cancel'. So, the code above checks for this, and returns -1 if the user did not make a choice because they closed the dialog somehow without clicking 'OK'.
I can't see an easy way to remove the close button of the dialog. It would be annoying anyway, because it would prevent them from closing the program or cancelling the test. It's best to let the user close/cancel the dialog if they really want to, and handle that situation as appropriate.
Also, it might be more user-friendly to show the choices as radio buttons (these things: (●) A, ( ) B, ( ) C) instead of a dropdown list. That way, the user can read all the choices at once without an extra click. Here's an alternative showQuestion method which does that, if you want. (It calls the dialog in a loop just in case the user did not select any option before clicking 'OK'.)
static int showQuestion(String dialogTitle, String question, String[] answers) {
Box box = new Box(BoxLayout.Y_AXIS);
box.add(new JLabel(question));
JRadioButton[] radioButtons = new JRadioButton[answers.length];
ButtonGroup buttonGroup = new ButtonGroup();
for (int i = 0; i < answers.length; i++) {
radioButtons[i] = new JRadioButton(answers[i]);
buttonGroup.add(radioButtons[i]);
box.add(radioButtons[i]);
}
for (;;) {
if (JOptionPane.CLOSED_OPTION == JOptionPane.showConfirmDialog(null, box, dialogTitle, JOptionPane.DEFAULT_OPTION)) {
return -1;
}
for (int i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].isSelected()) return i;
}
}
}
Edit: To return the answer directly instead of an index into the array, make a few small changes to the function above:
return type String instead of int.
return null instead of -1 when the user cancelled it
return answers[comboBox.getSelectedIndex()] instead of just comboBox.getSelectedIndex()
So it becomes:
static String showQuestion(String dialogTitle, String question, String[] answers) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(question), BorderLayout.NORTH);
JComboBox<String> comboBox = new JComboBox<>(answers);
panel.add(comboBox);
if (JOptionPane.CLOSED_OPTION == JOptionPane.showConfirmDialog(null, panel, dialogTitle, JOptionPane.DEFAULT_OPTION)) {
return null;
}
return answers[comboBox.getSelectedIndex()];
}
Then, the equivalent of the original snippet is:
Object contestacion5 = showQuestion("Examen Tijuanas PR", "#5 Que describe mejor a la Norteña?", new String[] {
"Ensalada de espinacas, tomates, zetas, cebolla, tocineta, aguacate, queso de hoja y tiras de maiz crujientes en vinagreta de la casa.",
"Lechuga romana servida con tomate, cebolla, maiz, aguacate, queso de hoja y tiritas de maiz crujientes acompañado de su seleccion de filetes de pollo de res.",
"Ensalada vegetariana de nopales, tomates, cebolla, lechuga romana, queso de hoja, aguacate, y aderezo especial de la casa.",
});

Categories

Resources