My program allows the user to repeatedly enter match results until the user enters 'stop', then the results are displayed. I just need to find the highest input value in my 'stats[2]' arraylist, which is the 'hometeam score'. So if the user enter 3 inputs, "Manchester City : Manchester United : 2 : 1 ...
Chelsea : Arsenal : 0 : 1 ...
Everton : Liverpool : 1 : 1" then it should display the number '2' as it's the highest value in that array. if that makes sense? I've set up the line at the bottom where I need it to be displayed.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); // initialize a container
// to hold all the stats
System.out.println("please enter match results:");
int matchesPlayed = 0;
int invalidEntry = 0;
while (sc.hasNextLine()) {
String input = sc.nextLine();
String[] results = input.split("\\s*:\\s*");
if (results.length == 4) {
stats.add(results);
matchesPlayed++;
}
else if (input.equals("stop")) {
break;
}
} // end of while
for (int i = 0; i < stats.size(); i++) {
if (stats.get(i)[0].trim().isEmpty()) {
System.out
.println("no home team name entered on the following line:");
invalidEntry++;
matchesPlayed--;
}
else if (stats.get(i)[1].trim().isEmpty()) {
System.out
.println("no away team name entered on the following line:");
invalidEntry++;
matchesPlayed--;
}
else if (stats.get(i)[2].trim().isEmpty()) {
System.out.println("no home score entered on this line");
invalidEntry++;
matchesPlayed--;
}
else if (stats.get(i)[3].trim().isEmpty()) {
System.out.println("no away score entered on this line");
invalidEntry++;
matchesPlayed--;
}
try {
System.out.println(String.valueOf(stats.get(i)[0]) + " ["
+ Integer.valueOf(stats.get(i)[2]) + "] " + " | "
+ (String.valueOf(stats.get(i)[1])
+ " [" + Integer.valueOf(stats.get(i)[3]) + "] "));
} catch (Exception e) {
// do nothing with any invalid input
}
}
System.out.println(" ");
System.out.println("Totals");
System.out.println("-------------------------");
System.out.println("total number of matches: " + matchesPlayed);
System.out.println("total number of invalid entries: " + invalidEntry);
System.out.println("highest home score: ");
}
Just loop through it, set a variable equal to the first element, and in the loop if there is an element that is higher than the variable currently is, change the variable's value to that. Then print the variable at the end
Related
do{
do{
System.out.print("Enter number" + count + ":");
if(scan.hasNextInt()){
d1 = scan.nextInt();
count ++;
}
else{
System.out.print("Number is invalid. ");
scan.next();
continue;
}
t+=d1;
}while(count<=5);
total = t / 5;
System.out.print("The average is :" + total + " ." );
System.out.print(" [do you want to continue press[ y ]for yes and [ n] for no ]:");
I tried placing the t+= inside and outside of the brackets but no good still the same result
this part is where I am confused because the t+=d1 will stack the more I loop e.g. all my 5 numbers is 25 then avg is 25 then I press y then loops back i enter same 5 of 25 then the avg is 50
welcome to StackOverflow.
Recommendation:
If you want a faster answer, share a runnable code.
ALWAYS indent your code, it will be easier to read.
The name of the variables are so important, so please, give them an appropriate name to know what they contain. (For example, you declared a variable "total" which will contain the average result, it will be reasonable to call it "avg" or "average")
this is a test class:
class StackOverflowTest {
// regex pattern
private static final String REGEX_Y_OR_N = "^[yn]$";
#Test
void execute() {
Scanner scan = new Scanner(System.in);
String needToContinue = "x";
// loop until the user press "n"
do {
// for each iteration, tot and count will be reinitialized
int tot = 0;
int count = 0;
// loop until the user enter 5 numbers
do {
System.out.print("Enter a number : ");
int input;
if (scan.hasNextInt()) {
input = scan.nextInt();
count++;
} else {
System.out.println("Number is invalid."+"\n");
scan.next();
continue;
}
tot += input;
} while (count < 5);
double avg = tot / 5;
System.out.println("The average is : " + avg + " .");
System.out.println("\n"+" [do you want to continue press [ y ] for yes and [ n ] for no ]: ");
// loop until a valid character is entered ("y" or "n")
do {
needToContinue = scan.next();
if (!needToContinue.matches(REGEX_Y_OR_N)) {
System.out.println("\n"+"Invalid character!"+"\n");
System.out.println(" [do you want to continue press [ y ] for yes and [ n ] for no ]: ");
}
} while (!needToContinue.matches(REGEX_Y_OR_N));
} while (needToContinue.contains("y"));
scan.close();
}
}
Have been up for hours trying to figure out how to add in these in a string array using user input and StringBuilder.
I have to in a loop collect names from user input (scanner).
when they enter a blank name stop looping. Then iterate over the attendee list to create the output string using StringBuilder.
only 1 name = Name .
2 names = Name 1 and name 2 . more then 2 names = name 1, name2, and name 3 . output should exactly match the way these are formatted with spaces, commas, and the "and".
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
sb.append("You have invited: ");
System.out.println("enter names.");
String attendee = keyboard.nextLine();
// receiving input
while (attendee != "") {
sb.append(attendee);
if (attendee == "") break;
}
System.out.println(sb);
for (int i = 0; i > sb.length(); i++) {
if (i == 0) {
keyboard.nextLine(); //consuming the <enter> from input above
sb.append(keyboard.nextLine());
i++;
} else if (i == 1) {
sb.append(keyboard.nextLine() + " and " + keyboard.nextLine());
System.out.println(sb);
} else if (i > 1) {
sb.append(keyboard.nextLine() + ", " + keyboard.nextLine() + ", and " + keyboard.nextLine());
System.out.println(sb);
}
}
}
There is a lot of errors in your code
you don't ask again in the while loop for a new value, so either you never get in (first empty string) or never get out (first not empty) also that isn't how you compare a string, that is an object, use .equals()
you may not call keyboard.nextLine() (getting input) in the loop where you build the output
names shouldn't be joined in the StringBuilder, then how would you build the output
So, make a nice loop that populates a list of String, then nicely concatenate the different parts to make the output
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> names = new ArrayList<>();
System.out.print("enter name: ");
String attendee = keyboard.nextLine();
while (!attendee.equals("")) {
names.add(attendee);
System.out.print("enter name: ");
attendee = keyboard.nextLine();
}
System.out.println(namesToString(names));
}
static String namesToString(List<String> names) {
List<String> firsts = names.subList(0, names.size() - 1);
String last = names.get(names.size() - 1);
if (names.size() == 1)
return "You have invited: " + last;
return "You have invited: " + String.join(", ", firsts) + " and " + last;
}
enter name: Patrick
enter name: Pierre
enter name: James
enter name: John
enter name:
You have invited: Patrick, Pierre, James and John
Full possibilities of outputs
System.out.println(namesToString(Arrays.asList("pierre")));
// You have invited: pierre
System.out.println(namesToString(Arrays.asList("pierre", "jean")));
// You have invited: pierre and jean
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude")));
// You have invited: pierre, jean and eude
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude", "john", "james")));
// You have invited: pierre, jean, eude, john and james
So in the code below i ask from the user first to enter some data and with pressing enter it goes to new line and writes the new one. If he writes END it shows him how many items they are stored and then he asks him again to choose from 1 to the list size of the items a number. After that i want to show him randomly some items depending the number he put. For example if he put 10 items at the first input and at the second he chose 5 to show him only 5 items randomly selected.
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
System.out.println(
"Δώστε στοιχεία προς κλήρωση (εισάγετε τα στοιχεία ένα ανά γραμμή - πατήστε ENTER για μετάβαση στην επόμενη γραμμή - πατήστε END για να λήξετε τη διαδικασία καταχώρησης)");
String input = scan.nextLine();
while (!input.equals("END")) {
list.add(input);
input = scan.nextLine();
}
System.out.println("Καταχωρήσατε " + list.size() + " στοιχεία στη λίστα");
Scanner scan2 = new Scanner(System.in);
System.out.println(
"Πόσα στοιχεία θέλετε να κληρωθούν; " + "(εισάγετε ακέραιο αριθμό από 1 έως " + list.size() + " )");
int user_num = scan2.nextInt();
while (user_num == 0 || user_num > list.size()) {
System.out.println("Eισάγετε ακέραιο αριθμό από 1 έως " + list.size());
user_num = scan2.nextInt();
}
Collections.shuffle(list);
System.out.println("Τα στοιχεία που κληρώθηκαν είναι:");
for (String word : list) {
System.out.println(word);
}
}
After the shuffling I print all the list items but i want only the items that the user chose that are saved in the variable user_num.
for (String word : list.subList(0,user_num) {
System.out.println(word);
}
Is this what you want? subList returns a new list with the elements specified by the indexes.
EDIT: to include index:
int index=1;
for (String word : list.subList(0,user_num) {
System.out.println((index++) + ". " + word);
}
I've been working on the same piece of java code for over a week now, t used to be a complete mess however i have got it now (through about a million iterations) to a somewhat working stage. The output i need is all three student names at the end with either a pass or fail beside their name, however my code will only output the last students name that i put in, completely ignoring the rest of the data i input.
If someone could teach me where i have gone wrong and also the quality of code i've produced and iterated, it would be much appreciated. Also to those who downvote my posts simply because it may seem easy to you, we aren't all experienced as you and don't forget that you used to be in my position once, so be thoughtful.
class Main extends BIO {
public static void main(String args[]) {
{
int i = 0;
int moduleMark = BIO.getInt();
String first_name = BIO.getString();
while (i++ < 3) {
System.out.print("Enter The Students name : ");
first_name = BIO.getString();
if (first_name.equals("END"))
break;
System.out.print("Their Module mark : ");
moduleMark = BIO.getInt();
}
if (moduleMark >= 40) {
System.out.println(first_name + " Pass");
} else {
System.out.println(first_name + " Fail");
}
}
}
}
first_name gets overwritten inside the loop constantly. When you exit the loop, first_name will be whatever the last name it received was.
If you can print them as you go, just print inside the loop. This will alternate between printing the results and asking for a new name/grade:
while (i++ < 3) {
System.out.print("Enter The Students name : ");
first_name = BIO.getString();
if (first_name.equals("END"))
break;
System.out.print("Their Module mark : ");
moduleMark = BIO.getInt();
if (moduleMark >= 40) {
System.out.println(first_name + " Pass");
} else {
System.out.println(first_name + " Fail");
}
If they must be printed at the end, you'll need to put the names and grades into lists, then iterate over the lists at the end:
// Create lists to hold grades and names
List<String> names = new ArrayList<>();
List<Integer> grades = new ArrayList<>();
while (i++ < 3) {
System.out.print("Enter The Students name : ");
first_name = BIO.getString();
if (first_name.equals("END"))
break;
// Add name to list
names.add(first_name);
System.out.print("Their Module mark : ");
moduleMark = BIO.getInt();
// Add grade to list
grades.add(moduleMark);
}
// Iterate both lists at once, printing inside the loop
for(int i = 0; i < names.size(); i++) {
String name = names.get(i);
Integer grade = grades.get(i);
if (grade >= 40) {
System.out.println(name + " Pass");
} else {
System.out.println(name + " Fail");
}
}
Im trying to count how many times each number between 0 to 9 was typed in a loop, when press -1 it will stop the loop, I made it work with the long term, Also I would have to print which of the numbers was typed the most.
For now I only have the couting code:
int pickedNum,counter_0=0,counter_1=0,counter_2=0,counter_3=0,counter_4=0,counter_5=0,counter_6=0,counter_7=0,counter_8=0,counter_9=0;
do{
System.out.println("Please enter a numbr between 0-9 , -1 to exit:");
pickedNum=s.nextInt();
if(pickedNum==0){
counter_0++;
}
if(pickedNum==1){
counter_1++;
}
if(pickedNum==2){
counter_2++;
}
if(pickedNum==3){
counter_3++;
}
if(pickedNum==4){
counter_4++;
}
if(pickedNum==5){
counter_5++;
}
if(pickedNum==6){
counter_6++;
}
if(pickedNum==7){
counter_7++;
}
if(pickedNum==8){
counter_8++;
}
if(pickedNum==9){
counter_9++;
}
}
while(pickedNum != -1);
System.out.printf("The number 0 appears: %d \n"
+ "The number 1 appears: %d \n"
+ "The number 2 appears: %d \n"
+ "The number 3 appears: %d \n"
+ "The number 4 appears: %d \n"
+ "The number 5 appears: %d \n"
+ "The number 6 appears: %d \n"
+ "The number 7 appears: %d \n"
+ "The number 8 appears: %d \n"
+ "The number 9 appears: %d \n",
counter_0,counter_1,counter_2,
counter_3,counter_4,counter_5,
counter_6,counter_7,counter_8,counter_9);
as you can see, It works fine, But I know there is a way better option to do this thing.
And as I mentioned, I also need to print the largest number counts(which number was type the most), and It will take a long way to reach that with my way of programming this.
I would like to get any tip or notes to improve this to work easier and faster.
Any notes would be appriciated.
EDIT:
Forgot to mention to use only basics, and not advanced methods, array and loops are fine.
int count[] = new int[10];
do{
counter[pickedNum]++;
} while(pickedNum != -1);
And then use counter[0], counter[1] etc in your print statement.
Don't forget that you can have more than one number that was typed the most, take a look at this :
public static void main(String[] args) throws ParseException {
int pickedNum, highestCounter = 0;
Scanner s = new Scanner(System.in);
int count[] = new int[10];
while (true) {
System.out.println("Please enter a numbr between 0-9 , -1 to exit:");
pickedNum = s.nextInt();
if (pickedNum != -1) {
count[pickedNum]++;
} else {
break;
}
}
int index1 = 0;
for (int i : count) {
System.out.println("The number " + index1 + " appears : " + i);
index1++;
}
// Finding the number was typed the most
for (int counter : count) {
if (counter > highestCounter) {
highestCounter = counter;
}
}
// In case if you have more than one number that was typed the most
Integer[] indexes = new Integer[10];
int index2 = 0;
for (int counter : count) {
if (highestCounter == counter) {
indexes[index2] = index2;
}
index2++;
}
System.out.print("The number(s) was typed the most is/are : ");
for (Integer i : indexes) {
if (i != null) {
System.out.print(i + ", ");
}
}
}
And the output :