Java Reading line with Scanner [duplicate] - java

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.

Related

JUnit test on recursive function (creating file and compare size)

I'm working on a project : copy a file and check if the size are equals. If not, delete file and redo it (number of retries is defined)
public boolean copieFichierAvecRetry(FileObject copieFichierFile, FileObject fichierACopier, int nbRetry, int currentNbRetry)
throws InterruptedException, IOException {
logger.logInfo("Deplacement du fichier " + fichierACopier.getName().getBaseName(),
"de " + fichierACopier.getParent().getName().getPath() + " vers "
+ copieFichierFile.getParent().getName().getPath());
copieFichierFile.copyFrom(fichierACopier, Selectors.SELECT_SELF);
boolean tailleOk = false;
// Si le flag de vérification est à true on vérifie que les fichiers
// copies ont la même taille
try {
tailleOk = verificationTailleCorrespondantes(copieFichierFile, fichierACopier);
if (!tailleOk && currentNbRetry <= nbRetry){
logger.logInfo("Erreur lors de la verification de la taille, essai n°" + currentNbRetry, null);
copieFichierFile.delete();
currentNbRetry++;
copieFichierAvecRetry(copieFichierFile, fichierACopier, nbRetry, currentNbRetry);
}
} catch (IOException e) {
logger.logWarn("Erreur lors de la verification de la taille : ", e.getMessage());
tailleOk = false;
}
return tailleOk;
}
Here is the unit test for the non-recursive function :
public void testCopieFichier()
throws IOException, InterruptedException, URISyntaxException, TransfertFichierException {
socleUtil.setNbTentativeMaxTransfert(1);
String nomFichierSource = "test123.txt";
String nomFichierDestination = "testDownloadSuccess.xml";
File fileOrigine = new File(getClass().getResource(SocleConstantes.SLASH).getFile());
String cheminFichierDistantOrigine = fileOrigine.getPath();
File fileDestination = new File(getClass().getResource(SocleConstantes.SLASH).toURI());
String cheminFichierDistantDestination = fileDestination.getPath() + FILE_SEPARATOR + "download";
assertTrue(socleUtil.copieFichier(
socleUtil.findFileLocal(cheminFichierDistantDestination + "/" + nomFichierDestination),
socleUtil.findFileLocal(cheminFichierDistantOrigine + "/" + nomFichierSource)));
assertTrue(fileDestination.exists());
}
As you can see in the code above, it will copy a file, check size and if it's OK then return true.
If it's false for 5 times (in the exemple) the function calls itself after deleting the file with wrong size.
verificationTailleCorrespondantes is the function to compare sizes.
tailleOk is true if both files are same size.
How should I test the recursivity of this function if it copies a file and never fail (which happens in production) ?
Thanks
In this case, I'd write the following scenarios:
the process success at its first iteration
the process fails at its (n-1)th iteration, success at its nth iteration with n < number of retries
the process fails at its nth iteration with n == number of retries
In order to do it, you'll need to mock your dependencies. Specially the one checking the file size. The mocking for the previous scenarios would be
file size check returns true. Assert that the check was run once and the result is valid
file size check returns false (n-1) times and true the nth time. Assert that the check was run n times and the result is valid
file size check returns false. Assert that the check was run number of retries times and the result is invalid

Selenium Webdriver (Java) - How to work around dynamic text and countdown timer?

I am working on automating a sign up that contains a counter.
So the thing is, I want to sign up to something that occurs every 7 minutes.
Here is what the web code looks like:
<class-countdown-timer _ngcontent-c19="" _nghost-c24="">
<!---->
<h2 _ngcontent-c24="" id="class-countdown-timer">Próxima clase en vivo en <span _ngcontent-c24="" class="countdown-timer">02:15</span>
<i _ngcontent-c24="" aria-hidden="true" class="icon-clock"></i>
</h2>
</class-countdown-timer>
My issue is that the "class-countdown-timer" text is dynamic and the "countdown-timer" its a countdown, from 07:00 to 00:00.
My cry for help is that I need to perform a certain action when the "class-countdown-timer" text is "Próxima clase en vivo en " and the counter is in between "05:00" and "02:00"
I can't get to work a fluent wait that waits until first, countdown text shows the above and the timer is between those times, any idea?
thanks :D
Try the below code :
// Count-down timer for looping upto 8 minutes
int countdown = 480;
while(countdown-->0) {
// Fetching the actual class-countdown-timer value
String actualTimerText = driver.findElement(By.id("class-countdown-timer")).getText().trim();
String expectedTimerText = "Próxima clase en vivo en ";
// Fetching the actual countdown-timer value
String countdownTimer = driver.findElement(By.xpath("//span[#class='countdown-timer']")).getText().trim();
// Converting the time for better comparing
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date expectedFirstTime = format.parse("05:00"), expectedSecondTime = format.parse("02:00");
Date actualCountdownTimer = format.parse(countdownTimer);
// Checking the condition if the 'class-countdown-timer' text is 'Próxima clase en vivo ee' and counter is in between '05:00' and '02:00' or not?
if(actualTimerText.equals(expectedTimerText) && ((actualCountdownTimer.equals(expectedSecondTime) || actualCountdownTimer.after(expectedSecondTime)) && (actualCountdownTimer.equals(expectedFirstTime) || actualCountdownTimer.before(expectedFirstTime)))) {
System.out.println("Condition Satisfied...");
// Do something
break;
}
// Waiting for one second before finding the element and checking the condition
Thread.sleep(1000);
}
The above approach is using the looping concept, iterate up to 8 minutes(480 seconds) until the required condition get satisfied.

How do I stop a while loop without exiting it (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

How can i avoid this format exception despite trim

EDIT : hidden character mess'd with my editor.
I want to read from my text file and add objects to an array from it. I'm getting a
NumberFormatException: For input string : "2".
If I remove the first line of the file, I get a format exception for input string "3".
What am I missing there ?
ArrayList<Personne> listp = new ArrayList<Personne>();
try {
FileReader file = new FileReader(personneFilePath);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] attributes = line.split(",");
listp.add(new Personne(Integer.parseInt(attributes[0].trim()), attributes[1], attributes[2], Double.parseDouble(attributes[3]), attributes[4], attributes[5], attributes[6]));
}
file.close();
} catch (FileNotFoundException e) {
System.out.println("Erreur 1 : " + e.getMessage());
} catch (IOException e) {
System.out.println("Erreur 2 : " + e.getMessage());
}
Here is the content of the file i'm reading;
2, Claire, Chazal, 65.0 , rue de Rennes, Laval, 53000
3, Jacques, Dupont, 90.0 , rue des Anges, Paris, 75000
4, Celine, Dia, 66.0 , rue Diderot, Paris, 75000
5, Remy, Cheval, 88.0 , rue du paradis, Nantes, 44000
It loosk like your file contains some unprintable characters near 2 which is not whitespace so trim() can't remove it.
To remove it you can use replaceAll("\\D","") instead of trim().
Better preferred solution would be removing cause of this problem, so set up your editor/file format/encoding properly and stop placing these characters in your file.
What you are doing looks fine.
I would recommend using debug mode (IntelliJ or Eclipse work well for this) and stepping into the Integer.parseInt method to see what input it is getting or where it fails.
Alternatively, add a print statement to see the value of attributes[0].trim(), maybe also the length of the string. It seems like there may be a non-printable character.

Regex Java word context

what I want to achieve is that I want to obtain the context of an acronym. Can you help me pls with the regular expression?
I am looping over the text (String) and looking for dots, after match I am trying to get the context of the particular found acronym, so that I can do some other processing after that, but I cant get the context. I need to take at least 5 words before and 5 words after the acronym.
//Pattern to match each word ending with dot
Pattern pattern = Pattern.compile("(\\w+)\\b([.])");
Matcher matchDot = pattern.matcher(textToCorrect);
while (matchDot.find()) {
System.out.println("zkratka ---"+matchDot.group()+" ---");
//5 words before and after tha match = context
// Matcher matchContext = Pattern.compile("(.{25})("+matchDot.group()+")(.{25})").matcher(textToCorrect);
Pattern patternContext = Pattern.compile("(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,10}"+matchDot.group()+"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,10}");
Matcher matchContext = patternContext.matcher(textToCorrect);
if (matchContext.find()) {
System.out.println("context: "+matchContext.group()+" :");
// System.out.println("context: "+matchContext.group(1)+" :");
// System.out.println("context: "+matchContext.group(2)+" :");
}
}
Example:
input:
Some 84% of Paris residents see fighting pol. as a priority and 54% supported a diesel ban in the city by 2020, according a poll carried out for the Journal du Dimanche.
output:
1-st regex will find pol.
2-nd regex will find "of Paris residents see fighting pol. as a priority and 54%"
Another example with more text
I need to loop through this once and every time I match an acronym to get the context of this particular acronym. After that I am processing some datamining. Here's the original text
neklidná nemocná, vyš. je možné provést pouze nativně
Na mozku je patrna hyperdenzita v počátečním úseku a. cerebri media
vlevo, vlevo se objevuje již smazání hranic mezi bazálními ganglii a
okolní bílou hmotou a mírná difuzní hypointenzita v periventrikulární
bílé hmotě. Kromě těchto čerstvých změn jsou patrné staré
postmalatické změny temporálně a parietookcipitálně vlevo. Oboustranně
jsou patrné vícečetné vaskulární mikroléze v centrum semiovale bilat.
Nejsou známky nitrolebního krvácení. skelet kalvy orientačně nihil tr.
Z á v ě r: Známky hyperakutní ischemie v povodí ACM vlevo, staré
postmalatickéé změny T,P a O vlevo, vaskulární mikroléze v centrum
semiovale bilat.
CT AG: vyš. po bolu k.l..
Po zklidnění nemocné se podařilo provést CT AG. Na krku je naznačený
kinkink na ACC vlevo a ACI vlevo pod bazí. Kalcifikace v karotických
sifonech nepůsobí hemodynamicky významné stenozy. Intrakraniálně je
patrný konický uzávěr operkulárního úseku a. cerebri media vlevo pro
parietální lalok. Ostatní nález na intrakraniálním tepenném řečišti je
v mezích normy.
Z á v ě r: uzávěr operkulárního úseku a. cerebri media vlevo.
Of course if it matches end of sentence is ok for me :-) The question is to find all the acronyms even if they are before new line (\n)
I would try this out:
(?:\w+\W+){5}((?:\w.?)+)(?:\w+\W+){5}
Though natural language processing with regular expressions cannot be accurate.
((?:[\w!##$%&*]+\s+){5}([\w!##$%&*]+\.)(?:\s+[\w!##$%&*]+){5})
Try this.See demo.
https://regex101.com/r/aQ3zJ3/9

Categories