Number instead of the candidates name change - java

import uulib.GUI;
import java.util.Scanner;
import uulib.Num;
/**
* Write a description of class votes1 here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class votes1
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String[]name=new String[6]; //candidates name
int[]vote=new int[6]; //candidates vote
int total_votes=0; //total votes
double[] percentage = new double[6]; //candidates percentage
int threshold=GUI.getInt("Enter threshold");
for(int i=0;i<name.length;i++){
System.out.println("Enter candidates last name");
name[i]=in.next();
System.out.println("Please enter the total votes for " + name[i]);
vote[i]=in.nextInt();
total_votes+=vote[i];
}
for(int i=0;i<vote.length;i++){
percentage[i]=(double) vote[i]/(double)total_votes*100.0;
}
int bel_threshold=vote[0];
int winner=vote[0];
for(int i=1;i<vote.length;i++)
{
if(vote[i]>winner)
{
winner=vote[i];
}
while(vote[i]<threshold){
bel_threshold=vote[i];
}
}
System.out.println("Candidate"+"\t"+"Votes"+"\t"+"%");
for(int i=0;i<vote.length;i++)
{
System.out.println(name[i]+"\t" + " \t"+vote[i]+"\t"+ Num.format(percentage[i],1));
System.out.println();
}
System.out.println("Total votes"+"\t" +total_votes);
System.out.println("Threshold" +"\t"+ threshold);
System.out.println("Winner: " + "\t" + winner);
System.out.println("Below threshold"+"\t" + " \t" + bel_threshold);
}
}
For the winner and below_threshold it shows the number of the low and high votes, i want to display the names of the candidates. How can i print the winner and below_threshold candidates name instead of their vote?

Keep the index in winner (not the votes). Like
int winner = 0;
for(int i=1;i<vote.length;i++)
{
if(vote[i]>vote[winner]){
winner = i;
}
}
Then print the winner like,
System.out.println("Winner: " + name[winner]);

String[ ] name:
+----+----+----+----+
| 0 | 1 | 2 | 3 | <--Array index
+----+----+----+----+
|Cdd1|Cdd2|Cdd3|Cdd4| <--Names of Candidates (String array)
+----+----+----+----+
int[ ] vote:
+----+----+----+----+
| 0 | 1 | 2 | 3 | <--Array index
+----+----+----+----+
|120 |550 |330 |220 | <--Votes of Candidates (int array)
+----+----+----+----+
This is what we call parallel arrays.
Meaning that same index corresponds to the same person.
Since the array index for name[] and vote[] matches,
the index of the highest vote will also be the index of the name (candidate)
with the highest vote.
Since you used winner to hold the index of the highest vote, just use winner again as the index to print out the name with the highest vote.
To print winner's name, simply do this:
System.out.println("Winner: " + "\t" + name[winner]);
It is easy to print out the names of the candidates below threshold. I think you don't need to store the candidates names right? You can just call a very simple method to do that:
public static void main(String[] args){
//Candidates below threshold
print_Below_Threshold(threshold, name, votes);
}
public static void print_Below_Threshold(int threshold, String[] name, int[] votes){
for(int x=0; x<name.legnth; x++)
if(votes[x] < threshold)
System.out.print(name[x] + " ");
}
If you are not allowed to use method for any reason, just write the 3 lines of codes directly in your main where you need to print the candidates below threshold.

Related

Need to get the index of the largest value in teamScores[] and print the associated string with the matching index from teamNames[]

Need to get the index of the largest value in teamScores[] and print the associated string with the matching index from teamNames[]. This is really starting to get on my nerves. I had been able to successfully get the right value for the scores printed but it kept printing the wrong team. When I was trying to troubleshoot I was getting the right team but the wrong score. I am absolutely lost and have no other ideas. Anybody offer some advice? I have to use two separate arrays so I cannot just reduce it to one array. I also have to use a for loop to retrieve the values, so I can't do like I did with the lowScore.
public class SmithJustin_Asgn6 {
public static int highScore(int[] teamScores, int highIndex) {
int max = teamScores[0];
for(int i = 0; i < teamScores.length; i++) {
if(max < teamScores[i]) {
max = teamScores[i];
highIndex = i;
}
}return highIndex;
}
public static int lowScore(int[] teamScores) {
Arrays.sort(teamScores);
int low = teamScores[0];
return low;
}
public static void main(String[] args) {
int highIndex = 0;
Scanner userInput=new Scanner(System.in);
Scanner scoreInput=new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams=scoreInput.nextInt();
int [] teamScores= new int[teams];
String [] teamNames= new String[teams];
for(int i = 0; i < teams; i++) {
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
String teamName=userInput.nextLine();
teamNames[i]=teamName;
System.out.print("Enter Team's score (400-1000): ");
int teamScore=scoreInput.nextInt();
teamScores[i]=teamScore;
System.out.println();
}
highScore(teamScores, highIndex);
lowScore(teamScores);
System.out.println();
System.out.println("The high score is "+ teamScores[highScore(teamScores, highIndex)] +" by team " + teamNames[highScore(teamScores, highIndex)] + " and the low score is "+ lowScore(teamScores) +".");
userInput.close();
scoreInput.close();
}
}
Been trying every way to slice it and I am completely stuck
You can create a class to store team name and its score. Then sort the array of class objects based on a comparator. Also, you don't need to use two Scanner objects.
class Team
{
public int score;
public String name;
}
class SmithJustin_Asgn6 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams = userInput.nextInt();
Team[] teamArray = new Team[teams];
for(int i = 0; i < teams; i++) {
teamArray[i] = new Team();
userInput.nextLine();
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
teamArray[i].name = userInput.nextLine();
System.out.print("Enter Team's score (400-1000): ");
teamArray[i].score = userInput.nextInt();
System.out.println();
}
userInput.close();
Arrays.sort(teamArray, new Comparator<Team>() {
#Override
public int compare(Team o1, Team o2) {
return Integer.compare(o1.score, o2.score);
}
});
System.out.println();
System.out.println("The high score is "+ teamArray[teams - 1].score +" by team " + teamArray[teams - 1].name + " and the low score is "+ teamArray[0].score +".");
}
}
As mentioned by #Andrey your Arrays.sort is the main culprit. You need a logic to get the low score index the same as you have done for high score index.
public static int lowScore(int[] teamScores, int lowIndex) {
// Arrays.sort(teamScores);
int low = teamScores[0];
//logic to low score's index
return lowIndex;
}
After you have both the indexes, you can easily get values from respective arrays using them.
In your main method you are calling the same methods multiple times instead of that you can do
int lowIndex = 0;
highIndex = highScore(teamScores, highIndex);
lowIndex = lowScore(teamScores, lowIndex);
System.out.println();
System.out.println("The high score is " + teamScores[highIndex] + " by team " + teamNames[highIndex] + " and the low score is " + teamScores[lowIndex] + ".");
Start learning stream. Its easy and fun ;).
int h1 = IntStream.range(0, teamScores.length)
.reduce((i, j) -> teamScores[i] > teamScores[i] ? i : j)
.getAsInt();
int lowScore = Arrays.stream(teamScores).min().getAsInt();
System.out.println("The high score is " + teamScores[h1] + " by team " + teamNames[h1]+ " and the low score is " + lowScore + ".");

How can I get the system output value after the whole loop is done?

this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);

User Input to determine the length of an array in Java

I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.

How do I calculate average of each subject

How do I calculate the average of each subject and average of the total value of 3 subjects and average of percentage and print them below the table.
I tried to find the average by dividing each array with number of students variable "DB" but it gives error
"The operator / is undefined for the argument type(s) int, int[][]".
And is there any way that I can get a perfect table structure for the output.
I'm using \t to create space between columns but they do not align properly.
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int DB[][],nos=0;
String S="";
Scanner s = new Scanner(System.in);
void Input()throws Exception
{
System.out.print("Enter The Number Of Students : ");
nos=Integer.parseInt(br.readLine());
DB=new int[nos+1][20];
String arrayOfNames[] = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter "+arrayOfNames[i]+"'s English Score : ");
DB[i][0]=Integer.parseInt(br.readLine());
System.out.print("Enter "+arrayOfNames[i]+"'s Science Score : ");
DB[i][1]=Integer.parseInt(br.readLine());
System.out.print("Enter "+arrayOfNames[i]+"'s Maths Score : ");
DB[i][2]=Integer.parseInt(br.readLine());
DB[i][3]=(int)(DB[i][0]+DB[i][1]+DB[i][2]);
DB[i][4]=((int)((DB[i][3])*100)/300);
DB[i][5]=(int)(DB[i][0])/DB;
Padd("Average\t",DB[i][5]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("Fail");
}
else {
System.out.print("Pass");
}
}
System.out.println("\n\n\nStudent Name. English Science \t Maths Total Percentage Pass or Fail \n");
for(int i=0;i<nos;i++)
{
System.out.print(""+arrayOfNames[i]+"\t\t");Padd("English \t ",DB[i][0]);Padd("Science \t ",DB[i][1]);
Padd("Maths \t ",DB[i][2]);Padd("Total \t",DB[i][3]);Padd("Percentage\t",DB[i][4]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("\t\tFail");
}
else {
System.out.print("\t\tPass");
}
System.out.println(S);
S="";
}
}
void Padd(String S,int n)
{
int N=n,Pad=0,size=S.length();
while(n!=0)
{
n/=10;
Pad++;
}
System.out.print(" "+N);
for(int i=0;i<size-Pad-4;i++)
System.out.print(" ");
}
public static void main(String args[])throws Exception
{
ReportCard obj=new ReportCard();
obj.Input();
}
}
Your problem is in this section of code
DB[i][5]=(int)(DB[i][0])/DB;
Padd("Average\t",DB[i][5]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("Fail");
}
else {
System.out.print("Pass");
}
From what I can understand from your code index 5 is not needed. You already stored the average in array index 4 (DB[i][4]).
Either way the division is illegal. An int cannot be divided by an array. Perhaps you mean the length of DB (DB.length)
You are getting this error as you are doing arithmetic operations on the array object itself.
Array in java is a data structure to hold sequential collection of values/objects. You can do arithmetic operations on elements of the array by accessing them using the index.
Like below:
int result = array[i][0] / 3;
But in your code you are passing entire array as an operand in the expression.
DB[i][5]=(int)(DB[i][0])/DB;
Above line of code is causing the issue. Instead of providing any entire DB array, provide it's corresponding index according to your requirement
I hope this answers your question

Using a for loop to find the greatest integer from an array of 5 integers

import java.util.*;
public class Project5{
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 5;
public static void main(String[] args){
Candidate[] candidateList = new Candidate[ARRAY_SIZE];
String name;
int votes;
int i = 0;
for (i = 0; i < ARRAY_SIZE; i++){
System.out.print("Enter Candidate #" + (i + 1) + " Name: ");
name = console.nextLine();
System.out.print("Please Enter the number of votes " + name + " Received: ");
votes = console.nextInt();
candidateList[i] = new Candidate(name, votes);
console.nextLine();
}
Candidate winner;
winner = candidateList[0];
This is where i have my issue, i have the for loop counting each of the five Strings i the Array but it doesn't seem to pick the String which has the most votes to be the winner. I feel like this is rather simple and it is simply flying over my head.
Also is what is the quickest way to simplify this part here?
System.out.print(" Candidate Votes Recieved % of Total Votes");
System.out.print("\n");
System.out.print("\n");
One more thing, is there a way to simply have a code like this but in one format? So like {System.out.print(candidateList[i].getCandidateInfo());}
System.out.print(candidateList[0].getCandidateInfo());
System.out.print(candidateList[1].getCandidateInfo());
System.out.print(candidateList[2].getCandidateInfo());
System.out.print(candidateList[3].getCandidateInfo());
System.out.print(candidateList[4].getCandidateInfo());
System.out.print("The winner is: " + winner);
}
}
Like Berger said "Remove the else winner = candidateList[0];".
System.out.print(" Candidate Votes Recieved % of Total Votes\n"\n"");
No. I would override the toString() method though in you Candidate class, to confirm more to standards. Then call candidateList[0].toString().
Or you could do it in a loop:
for (i = 0; i < ARRAY_SIZE; i++){
System.out.print(candidateList[i].getCandidateInfo());
}
I would suggest implement Comparable Interface to your Candidate class and implement the
public int compareTo(Candidate candidate) {
int votes = Candidate.getCVotes();
//descending order
//return votes - this.cVotes;
}
Instead of for loop do
Arrays.sort(candidateList)
The 0th element after sorting will be the winner.
This way if tomorrow you need to know the 2nd and 3rd position holder you can simply print 1 and 2 indexed element from your candidateList.

Categories

Resources