explain to me while in this code, even though I am able to ask the user for
Question:
explain to me while in this code, even though I am able to ask the user for an integer, it is now printing out the name twice.
For example, if the user enters john and then enters john for the integer, it will throw an exception, then I might type the integer 20. But once I type in end, it is printing out the name john two times. Where am I going wrong?
import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; import java.util.Scanner;
public class Problem25 {
public static void main(String[] args) throws java.io.IOException{
java.io.File file = new java.io.File("Problem25.txt"); if (file.exists()) { System.out.println("file already exists"); System.exit(1); } try (java.io.PrintWriter output = new java.io.PrintWriter(file);) { ArrayList drivers = new ArrayList(); ArrayList scores = new ArrayList();
Scanner userInput = new Scanner (System.in); String name; int score; System.out.println("Please enter a race car drivers name, hit enter, then add their score, followed by the enter key (to add more drivers). " + "Once you are done adding drivers and their scores, type end to sort the drivers in descending order."); while(true) { name = userInput.next(); if(name.equalsIgnoreCase("end")) { break; } drivers.add(name); try { score = userInput.nextInt(); scores.add(score); } catch(InputMismatchException ex) { System.out.println("not an integer, please enter an integer."); } } for (int i = 0; i < scores.size(); i++) { int maxIdx = i; for(int j = i + 1; j < scores.size();j ++) { if(scores.get(maxIdx)< scores.get(j)) { maxIdx = j; } } int tempScore = scores.get(i); scores.set(i, scores.get(maxIdx)); scores.set(maxIdx, tempScore); String tempName = drivers.get(i); drivers.set(i, drivers.get(maxIdx)); drivers.set(maxIdx, tempName); } for (int i = 0; i < drivers.size()-1; i++) { output.print(drivers.get(i) + ", "); } output.print(drivers.get(drivers.size()-1) + " "); for (int i = 0; i < scores.size()-1; i++) { output.print(scores.get(i) + ", "); } output.print(scores.get(scores.size()-1) + " "); userInput.close(); output.close(); } } }
Microsoft Visual C# An Introduction to Object-Oriented Programming
ISBN: 978-1337102100
7th edition
Authors: Joyce Farrell