How do I stop a while loop without exiting it (Java) - java

Hello so I have a question to Java (I'm new so dont excpext too much).
I want to just print everything from the method once and not the whole time.
The method is called 'kuehlschrankInformationen'.
So my question is, how do I just run the methode once and then he starts me asking again, what I want to do. Here is the code(the text is german but I guess it wont make any difference):
System.out.println("Geben Sie ein, was Sie mit dem Kühlschrank machen wollen:");
USER_INPUT = input.nextLine();
while(true){
if (USER_INPUT.equalsIgnoreCase("Ich möchte meinen Kühlschrank schließen")){
TimeUnit.SECONDS.sleep(1);
System.out.println("Das System wird nun herunter gefahren, bis bald");
TimeUnit.SECONDS.sleep(3);
System.exit(0);
}
else if (USER_INPUT.equalsIgnoreCase("Was ist die derzeitige Temperatur im Kühlschrank")){
kuehlschrankTemperatur();
}
else if (USER_INPUT.equalsIgnoreCase("Zeigen Sie mir Informationen über den Kühlschrank an")){
kuehlschrankInformationen();
}
}
And here is the methods code:
public void kuehlschrankInformationen(){
dimensionen = "Die Breite beträgt 178cm, die Höhe 66,8cm & die Länge 59,5cm";
verbrauch = 157;
volumen = 707.5; // in liter
name = "Build Your Body Fat";
gewicht = 63;
try{
System.out.println(name);
System.out.println(gewicht);
System.out.println(volumen +" Liter");
System.out.println("Der Kühlschrank verbraucht " + verbrauch + "kWh");
System.out.println(dimensionen);
TimeUnit.SECONDS.sleep(5);
I would be pretty thankful, if you could help me out

If you want to stop executing the method you put the return statement in the end of this method, if you want to skip an iteration you put continue in your loop skipping one iteration. And if you put break your loop stops and not the method.
I believe you're looking for break
Read the docs while loop

Related

SoupPVP RIGHT_CLICK_AIR?

Hallo Leute Ich wollte ein Minecraft Plugin Programmieren,
dabei ist mir ein Fehler auf gefallen.
Hello I wanted to program a Minecraft plugin, and I noticed a mistake.
public void onIteract(PlayerInteractEvent e) {
try {
if(e.getAction().equals(Action.RIGHT_CLICK_AIR)|| e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Player p = e.getPlayer();
ItemStack bowl = new ItemStack(Material.BOWL);
if(e.getMaterial() == Material.MUSHROOM_SOUP) {
double i = p.getHealth();
if(i != 20) {
if(i > 11) {
p.setHealth(20);
p.getInventory().setItemInHand(bowl);
p.playSound(p.getLocation(), Sound.EAT, 1, 1);
} else {
p.setHealth(i + 8);
p.getInventory().setItemInHand(bowl);
p.playSound(p.getLocation(), Sound.EAT, 1, 1);
}
}
}
}
}catch (Exception exception) {
}
}
und zwar funktioniert dieser code ohne Probleme aber wen ich die soup "MUSHROOM_SOUP" in der Luft rechst klick funktioniert p.getInventory().setItemInHand(bowl); nicht zumindest bekomme ich sie nicht gesetzt.
this code works without problems but when I right click the soup "MUSHROOM_SOUP" in the air it works p.getInventory().setItemInHand(bowl); at least I don't get it set.
Danke bei der Hilfe ;)
MC-Version: 1.8.9 / Spigot
Here are the issues with your code:
Don't catch all exceptions without a reason to. If an exception is thrown in your onInteract method, then there is something wrong with your code.
a.equals(b) is to compare Strings, use a == b for objects other than Strings.
You spelt onInteract incorrectly.
More of a nitpick, but you should name variables with words, not just letters.
e.getMaterial() isn't a valid method. You need to access the player's inventory, get the ItemStack in their hand, and get the Material (type) of the item.
The big block limiting the health to 20 is unnecessary, when you can set the health to Math.min(20, value). This forces the health to be set no higher than 20.
I haven't tested this, but I believe this will work.
public void onInteract(final PlayerInteractEvent event) {
if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
final Player player = event.getPlayer();
if(player.getInventory().getItemInHand().getType() == Material.MUSHROOM_SOUP) {
player.setHealth(Math.min(20, player.getHealth() + 8));
player.playSound(player.getLocation(), Sound.EAT, 1, 1);
p.getInventory().setItemInHand(new ItemStack(Material.BOWL, 1));
}
}
}
Ways you can improve this further:
Instead of using the number 20, get the player's max health, as it could be higher than 20 on some servers.
Play a particle, i.e. the one from mushroom soup, when it is consumed.
Add hunger points to the player.
Feel free to contact me on SpigotMC (#lokka30) if you wish to contact me - I rarely check this website.

How to fix 'SQLException SQL0913' after calling SQL update in different threads

I'm calling a method, that does an SQL UPDATE on a single dataset in a DB2 database. The method is called automatically in different threads after receiving message from an ActiveMQ queue. It is called 5 times in 2 seconds, but because the first call sets a WRITE-Lock on the dataset, the next 3 calls have to wait. After the first call finishes the update, the second call is not executing the update, instead, a new method call (the 5th call in the row) runs through. The Problem is, that the three calls in between are not recognizing, that the WRITE-Lock was released, and are throwing a SQLException with error SQL0913 after a timeout of 1 minute.
Caused by: java.sql.SQLException: [SQL0913] Zeile oder Objekt PR1BAFPU5 der Art *FILE in DAKDTA wird verwendet. Ursache . . . . : Das angeforderte Objekt PR1BAFPU5 der Art *FILE in der Bibliothek DAKDTA wird gerade von einem anderen Anwendungsprozess verwendet, oder eine Zeile im Objekt wird von einem anderen Anwendungsprozess oder einem anderen Cursor in diesem Anwendungsprozess verwendet. Fehlerbeseitigung: Die vorherigen Nachrichten im Jobprotokoll aufrufen (Befehl DSPJOBLOG) oder im interaktiven SQL F10 (Nachrichten im Jobprotokoll anzeigen) in dieser Anzeige drücken, um zu bestimmen, ob es sich um eine Wartezeitüberschreitung für eine Objekt- oder Satzsperre handelt. Einen der folgenden Schritte durchführen: -- Wird ein Objekt durch einen anderen Anwendungsprozess gesperrt, die SQL-Anweisung wiederholen, wenn das Objekt nicht verwendet wird. Mit dem Befehl WRKOBJLCK (Mit Objektsperren arbeiten) kann festgestellt werden, von wem das Objekt gerade verwendet wird. -- Ist das Objekt ein Schema und wurde versucht, in diesem Schema eine Tabelle, eine Sicht oder einen Index unter COMMIT-Steuerung zu erstellen, wird möglicherweise für dieses Schema gerade eine Operation zum "Sichern im aktiven Zustand" von einem anderen Job im System durchgeführt. Ist die Operation zum "Sichern im aktiven Zustand" abgeschlossen, die Anforderung wiederholen. -- Wird ein Satz durch einen anderen Anwendungsprozess gesperrt, die SQL-Anweisung wiederholen, wenn der Satz nicht verwendet wird. Mit dem Befehl DSPRCDLCK (Satzsperren anzeigen)kann festgestellt werden, von wem der Satz gerade verwendet wird. -- Wird der Satz von einem anderen Cursor in demselben Anwendungsprozess gesperrt, muss eine Anweisung COMMIT, ROLLBACK oder eine andere Anweisung FETCH für den Cursor ausgegeben werden, der die Sperre verursacht, bevor diese SQL-Anweisung ausgegeben wird. Tritt dieser Fehler häufig auf, mit dem Befehl CHGPF (Physische Datei ändern), CHGLF (Logische Datei ändern) oder OVRDBF (Datenbankdatei überschreiben) die Wartezeitüberschreitung für das Objekt oder den Satz ändern.
at com.ibm.as400.access.JDError.createSQLExceptionSubClass(JDError.java:860) [jt400-jdbc4-7.8.jar:JTOpen 7.8]
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:692) [jt400-jdbc4-7.8.jar:JTOpen 7.8]
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:662) [jt400-jdbc4-7.8.jar:JTOpen 7.8]
at com.ibm.as400.access.AS400JDBCStatement.commonExecute(AS400JDBCStatement.java:1025) [jt400-jdbc4-7.8.jar:JTOpen 7.8]
at com.ibm.as400.access.AS400JDBCPreparedStatement.executeUpdate(AS400JDBCPreparedStatement.java:1649) [jt400-jdbc4-7.8.jar:JTOpen 7.8]
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:493)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186) [hibernate-core-4.2.27.Final-redhat-1.jar:4.2.27.Final-redhat-1]
... 143 more
The database is a IBM DB2 database (version 7.2), and my program is running on a JBoss EAP-6.4. From the logs, it looks like that the first call takes several seconds to execute, in between the next three calls are waiting for the first one. But after the first one finished execution, the next three calls are not proceeding.
public void updateBerthTimeConflictFlag4BerthArrival(boolean conflict, String berthArrivalId) {
Query updateQuery = em.createNativeQuery("update PR1BERTHARRIVAL_FLZ set berthTimeConflict = :conflict where id = :id");
updateQuery.setParameter("conflict", conflict ? 1 : 0);
updateQuery.setParameter("id", berthArrivalId);
updateQuery.executeUpdate();
}
I would expect, that after the first call finishes, the next three calls of the SQL update are executed in the order of the call.
We had the same problem times ago, and we follow this:
Problem(Abstract)
When an application reads a number of records using JDBC from a table and uses a BMP entity bean to delete the records from the table, the error "java.sql.SQLException: [SQL0913] Row or object F55500 in type *FILE in use" occurs.
Cause
The exception indicates that the rows or objects are in use.
Resolving the problem
In the JDBC program that reads a number of records, you need to ensure that all connections are closed so that all resources are released.
If there is no direct way for releasing the connection, restarting the database would remove any open connections but this would be a last measure if there is no other alternative for release the connections.
Instead of using a JDBC program, create a separate session bean to contain the query to the database. The session bean should have a transaction setting of RequiresNew. The SQL statement now runs in a new separate transaction. Once the method has completed running, the transaction is ended and the tables are freed to be used by the BMP entity beans to delete.
Here the original technote

Read tab delimited file and ignore empty space

I am working on a simple project in which a tab delimited text file is read into a program.
My problem:
When reading the text file there are regularly empty data spaces. This lack of data is causing an unexpected output. For lines that do not have data in the token[4] position all data read is ignored and "4" is displayed when I run a System.out.println(Just a test that the data is being read properly). When I incorporate a value in the token[4] position the data reads fine. It is not acceptable that I input a value in the token[4] position. See below for file and code.
2014 Employee Edward Rodrigo 6500
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
2015 Employee Bernie Johnson 5500
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
2015 Employee Kevin Bolden 9200
2015 Employee Thomas Sullivan 6250
My code is:
// Imports are here
import java.io.*;
import java.util.*;
public class EmployeeData {
public static void main(String[] args) throws IOException {
// Initialize variables
String FILE = "employees.txt"; // Constant for file name to be read
ArrayList<Employee> emp2014; // Array list for 2014 employees
ArrayList<Employee> emp2015; // Array list for 2015 employees
Scanner scan;
// Try statement for error handling
try {
scan = new Scanner(new BufferedReader(new FileReader(FILE)));
emp2014 = new ArrayList();
emp2015 = new ArrayList();
// While loop to read FILE
while (scan.hasNextLine()) {
String l = scan.nextLine();
String[] token = l.split("\t");
try {
String year = token[0];
String type = token[1];
String name = token[2];
String monthly = token[3];
String bonus = token[4];
System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
} catch (Exception a) {
System.out.println(a.getMessage());
}
}
} catch(Exception b) {
System.out.println(b.getMessage());
}
}
}
The output I receive for lines with "Employee" returns in an unexpected way.
Output:
run:
4
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
4
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
4
4
BUILD SUCCESSFUL (total time: 0 seconds)
I tried to use an if-then to test for null value in token[4] position but that didn't really help me. I've done quite a bit of searching with no success.
I am still very new to the programming world, so please pardon my coding inefficiencies. Any support and general feedback to improve my skills is greatly appreciated!
Thank you,
Bryan
Java Devil is right that the underlying issue because of an ArrayOutOfBoundsException. But it's also worth exploring why you didn't see that. As we discussed in the comments your "Try statement for error handling" is in fact not handling your errors at all, instead it is suppressing them, which is generally a poor plan as it allows your program to continue running even after your assumption (that it works correctly) has been violated.
Here's a slightly cleaned up version of your code. The underlying problem that causes the ArrayOutOfBoundsException is still there, but the issue would be immediately apparent if you'd structured your code this way instead. There's a few comments calling out issues inline.
public class EmployeeData {
// constants should be declared static and final, and not inside main
private static final String FILE = "employees.txt";
// If you have an exception and you don't know how to handle it the best thing
// to do is throw it higher and let the caller of your method decide what to do.
// If there's *nothing* you want to do with an exception allow main() to throw
// it as you do here; your program will crash, but that's a good thing!
public static void main(String[] args) throws IOException {
// Notice the <> after ArrayList - without it you're defining a "raw type"
// which is bad - https://stackoverflow.com/q/2770321/113632
ArrayList<Employee> emp2014 = new ArrayList<>();
ArrayList<Employee> emp2015 = new ArrayList<>();
// A try-with-resources block automatically closes the file once you exit the block
// https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (Scanner scan = new Scanner(new BufferedReader(new FileReader(FILE)))) {
while (scan.hasNextLine()) {
String l = scan.nextLine();
String[] token = l.split("\t");
// The code below this line assumes that token has at least five indicies;
// since that isn't always true you need to handle that edge case before
// accessing the array indicies directly.
String year = token[0];
String type = token[1];
String name = token[2];
String monthly = token[3];
String bonus = token[4];
System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
}
}
}
}
This is happening because you are actually getting an ArrayOutOfBoundsException and the message for that is '4'. Because the index of 4 is greater than the length of the array. You should put in your catch statement b.printStackTrace() as this will give you greater details when ever the caught exception occurs.
You can get around this by adding the following:
String bonus = "";
if(token.length > 4)
bonus = token[4];

Search database with multiple keywords separated by a comma

I have been trying for several days to write a search function where you can enter multiple keywords to output all lines that have these words stored in the respective column.
Searching for a single term is not a problem.
Here is my code:
private void StartSearchTagsTextKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode()==KeyEvent.VK_ENTER) {
try {
String sql = "SELECT ID, Titel, Autor, Regal, Fach, Gelesen, Tags FROM TableDB WHERE UPPER(Tags) LIKE UPPER(?) "; // hinter select kommt entweder ein * wenn alle spalteninhalte angezeigt werden sollen oder der jeweilige spaltenname welche angezeigt werden sollen
pst = conn.prepareStatement(sql);
pst.setString (1, "%" +StartSearchTagsText.getText()+ "%");
rs= pst.executeQuery ();
StartTable.setModel (DbUtils.resultSetToTableModel(rs));
pst.close();
StartSearchTagsText.setText("");
}
catch (SQLException e) {
JOptionPane.showMessageDialog (null, "searchtagskey");
}
}
}
I hope someone has a suggestion.
String searchterm1 = "Herrmann";
String searchterm2 = "Die kleine Hexe";
String sql = "Select * from TableDB where Autor like ? and Titel like ?";
pst = conn.prepareStatement(sql);
pst.setString (1, searchterm1);
pst.setString (2, searchterm2);
It should work like that.
This should be the simplest solution. If you can tell us what DBMS you are using we might be able to make it shorter depending on the system used.
First of all: LIKE only works with a single value for each evaluation it does. You can't separate it by commas like in the IN statement for example.
Therefore I'd suggest that you split the value of StartSearchTagsText.getText() into an array using the the .split("DELIMITER") function.
Then you can use a loop to add "OR LIKE %" + yourArray[i] + "%" to your sql String for every term you want to search for. (lose the OR for the first pass of the loop)
Du kannst mit LIKE nicht mehrere Bedingungen evaluieren, wie es z.B. mit IN geht.
Ich würde vorschlagen, dass du dir ein Array mit den gesplitteten Werten deines Textfeldes erzeugst. Das geht mit .split("TRENNUNGSZEICHEN"). Das Trennungszeichen musst du entsprechend anpassen. Wenn ein Komma die einzelnen Wörter nach denen du suchen willst separiert, dann schreibst du statt TRENNUNGSZEICHEN entsprechend ein , in die Klammer.
Sobald du das Array hast, kannst du es einfach komplett durchlaufen und bei jedem Durchlauf dein SQL-Statement mit "OR LIKE %" + deinArray[i] + "%"erweitern. Beim ersten Durchlauf das OR weglassen. Dann liefert dir das SELECT alle Datensätze zurück, was einem der Begriffe aus deinem Textfeld entspricht.

Java Reading line with Scanner [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I'm new to java world,
I'm writing a simple program but i'm having a problem :
here's the code :
while(choix!=7) {
System.out.println("Tapez un choix :") ;
choix=s.nextInt();
switch (choix) {
case 1 : { } break ;
case 2 :{
c.vider() ; }break ;
case 3 :{
int i,n; System.out.println("donnez le nombree de livres à ajouter");
n=s.nextInt();
for(i=0;i<n;i++) c.ajouter() ;
}break ;
case 4:{
c.Index() ;
c.affichagemotsvides();
c.affichageindex();
} break ;
case 5 :{
//s.wait();
String aut ;
System.out.println("Tapez le nom de l'auteur");
aut=s.nextLine() ; //Here's the line where i want to read the string
if (aut !=null)
System.out.println("==========>"+aut);
//livre l1 =new livre();
//l1=c.rechercheAut(aut);
//l1.afficher();
}break ;
The first time i enter a number choix=s.nextInt();
its readed correctly when i put 5 .
the aut=s.nextLine() ; don't let me write the string i want to enter.
Here's the output :
1. Créer un Catalogue
2. Vider le Catalogue
3. Ajouter des livres dans le Catalogue
4. Générer l’Index du Catalogue
5. Rechercher dans le Catalogue, par Auteur
6. Rechercher dans le Catalogue, par Mot Clé
7. Quitter
Tapez un choix :
5
Tapez le nom de l'auteur
==========>
Tapez un choix :
add s.nextLine() ; before aut=s.nextLine() ;
i.e.
try
s.nextLine()
aut=s.nextLine() ;
Explanation :as Bohemian said in given link Scanner issue when using nextLine after nextXXX
it's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". When input.nextLine() executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine() immediately after input.nextInt()
After the nextInt() you still have the rest of the line (even if it is blank and you didn't type anything after the integer)
This means the nextLine() will read what you types after the integer.
Most likely you want to ignore everything after the integer so I suggest you do this.
choix = s.nextInt();
s.nextLine(); // ignore the rest of the line.

Categories