I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!
Related
I have programmed a working voting system, but it needs a little more decision making involved. The program needs to work if two or more candidates have the same number of votes.
Below is what i have but i think it is very long winded, and it will only work with 2 candidates having the same number of votes. Is there a more efficient way of doing this while working with 2 or more candidates having the same votes.
There are only 5 candidates available in this scenario, but should work if more are added too.
if(numArray[0] == numArray[1]){
System.out.println("\nIn third place: " + Array[3]);
System.out.println("In second place: " + Array[2]);
System.out.println("And the winner is: " + Array[0] + " and " + Array[1]);
}else if(numArray[1] == numArray[2]){
System.out.println("\nIn third place: " + Array[3]);
System.out.println("In second place: " + Array[1] + " and " + Array[2]);
System.out.println("And the winner is: " + Array[0]);
}else if(numArray[2] == numArray[3]){
System.out.println("\nIn third place: " + Array[2] + " and " + Array[3]);
System.out.println("In second place: " + Array[1]);
System.out.println("And the winner is: " + Array[0]);
}else{
System.out.println("\third place: " + Array[2]);
System.out.println("second place: " + Array[1]);
System.out.println("winner is: " + Array[0]);
}
I'd first check what are the scores, highest, second highest, third highest.
And then pick the names which have these values
public static void displayFinalResults(String[] stringArray, int[] numArray){
int highestScore = max(numArray, Integer.MAX_VALUE);
int secondHighestScore = max(numArray, highestScore);
int thirdHighestScore = max(numArray, secondHighestScore);
System.out.println("\nIn third place: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == thirdHighestScore) {
System.out.println(stringArray[i]);
}
}
System.out.println("In second place: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == secondHighestScore) {
System.out.println(stringArray[i]);
}
}
System.out.println("And the winner: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == highestScore) {
System.out.println(stringArray[i]);
}
}
}
public static int max(int[] scores, int lessThan) {
int max = Integer.MIN_VALUE;
for (int score : scores) {
if (score > max && score < lessThan) {
max = score;
}
}
return max;
}
This is approach I would take. I would create a structure to hold the candidate name and number of votes as tracking that across 2 arrays is complicated and might be confusing. I would also suggest to use different data structures than arrays as the method input, I converted the input in the example into stream of Candidate which has 2 fields name and numVotes:
record Candidate(String name, int numVotes) {
}
public static void displayFinalResults(String[] stringArray, int[] numArray) {
//make sure that 2 arrays match in size
assert numArray.length == stringArray.length;
//zip arrays and convert to the stream of Candidate
var candidates = IntStream.range(0, stringArray.length).mapToObj(i -> new Candidate(stringArray[i], numArray[i]));
//group by number of votes
var groupedByNumVotes = candidates.collect(Collectors.groupingBy(c -> c.numVotes));
//sort by number of votes descending
var sorded = groupedByNumVotes.entrySet().stream().sorted((e1, e2) -> Integer.compare(e2.getKey(), e1.getKey()));
//take first 3 places
var winners = sorded.limit(3).toList();
//Loop through the list of winners with index and print it
for (int i = 0; i < winners.size(); i++) {
//List is indexed from 0 so the place number needs to be increased by one
System.out.println("Place " + (i + 1));
winners.get(i).getValue().forEach(System.out::println);
System.out.println();
}
}
Frankly, there is nothing fundamentally wrong with your approach (except that, by convention, the second place is usually skipped if there is a tie for the first; that is: there are two tied first-place candidates and a third place, but no second place). You just need to add one more case for three tied candidates.
That said, you can slightly shorten the code by merging redundancies in output formatting:
public static void displayFinalResults(String[] names, int[] scores) {
final String[] winners = new String[3];
if (scores[0] == scores[1] && scores[1] == scores[2]) {
winners[0] = String.format("%s, %s and %s", names[0], names[1], names[2]);
} else if (scores[0] == scores[1]) {
winners[0] = String.format("%s and %s", names[0], names[1]);
winners[2] = names[2];
} else if (scores[1] == scores[2]) {
winners[0] = names[0];
winners[1] = String.format("%s and %s", names[1], names[2]);
} else {
System.arraycopy(names, 0, winners, 0, 3);
}
System.out.println();
if (winners[2] != null) System.out.printf("In third place: %s\n", winners[2]);
if (winners[1] != null) System.out.printf("In second place: %s\n", winners[1]);
final String prefix = winners[2] == null && winners[1] == null ? "T" : "And t";
System.out.printf("%she winner is: %s\n", prefix, winners[0]);
}
This is my first doubt here, i'm really noob on this and my english isn't the best, so first of all sorry if there's a dummie mistake.
The thing is that I want to do a for loop to save every user input from console and add it to a list named "Order". This action have to be done if the user type correctly the order and it have to be checked to know if that exists on the menu. If it doesn't we have to let the user know the situation and ask him/her if he/she wants something we have on the menu. Also after every input saved on the listed we want to ask the user if he/she wants to order something more, so if is YES the loop have to be initialized and if is NO we have to get out the loop.
The problem with my code is that no matter what I type in the console, the loop is done from start to finish every cicle.
Where is the error?
Thanks!!!
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Fase2_final {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] menu = { "chicken", "steak", "hamburger", "spaghettis", "pizza" };
int[] price = { 10, 15, 20, 5, 12 };
boolean order = true;
for (int i = 0; i < menu.length; i++) {
System.out.println("We have " + menu[i] + " for " + price[i] + "€");
}
int yes = 1;
int no = 0;
Scanner yesOrNo = new Scanner(System.in);
System.out.println("What do you want to eat?");
List<String> Order = new ArrayList<String>();
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
} else if (yesOrNo.nextInt() == no) {
System.out.println("Order finished!");
}
}
} while (yesOrNo.nextInt() == yes);
}
}```
There is no need to re-declare the Scanner object every iteration, or to have more than one Scanner object that will read from the same source. Also, there is no need to print out "I didn't find it!" over every comparison.
Consider the following block of code:
.
.
.
// there is no need to re-declare the Scanner object every iteration, or two scanners
Scanner keyboard = new Scanner(System.in);
do {
String userOrder = keyboard.next().toLowerCase();
// we haven't found the item
boolean found = false;
// integer option (yes or no)
int option;
// do the search
for (int j = 0; j < menu.length; j++) {
// do this if found
if (userOrder.equals(menu[j])) {
// set flag to indicate we found the item
found = true;
// add the order
Order.add(userOrder);
// print out, then read the user's option
System.out.println("You ordered" + userOrder + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
option = keyboard.nextInt();
// consume the NL leftover from the nextInt() call
keyboard.nextLine();
// break out of the for loop since you already found what you're looking for
break;
}
}
// check if you didn't find the item
if (!found) {
// print out
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
// read if user wants to continue
option = keyboard.nextInt();
// consume the NL leftover from the nextInt() call
keyboard.nextLine();
}
} while (option == yes);
System.out.println("Order finished!");
.
.
.
// close the scanner when you're done
keyboard.close();
.
.
.
I have refactored your code . try to see in comparing tool .
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Fase2_final {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] menu = { "chicken", "steak", "hamburger", "spaghettis", "pizza" };
int[] price = { 10, 15, 20, 5, 12 };
boolean order = true;
for (int i = 0; i < menu.length; i++) {
System.out.println("We have " + menu[i] + " for " + price[i] + "€");
}
int decision = 0;
int yes = 1;
int no = 0;
Scanner yesOrNo = new Scanner(System.in);
System.out.println("What do you want to eat?");
List<String> Order = new ArrayList<String>();
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
}
}
decision = yesOrNo.nextInt();
if (decision == no) {
System.out.println("Order finished!");
}
} while (decision == yes);
}
}
Always close the scanner when you are done .
the nextInt() method returns the current input one time, if you call it twice it needs a second input. It could should look like this:
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
int answer = 0;
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
} else if ((answer = yesOrNo.nextInt()) == no) {
System.out.println("Order finished!");
}
}
} while (yesOrNo.nextInt() == answer);
I hope I answered your question.
My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?
Code:
package SMKTeamStandings;
import java.util.Scanner;
public class SMKTeamStandings {
public static Scanner in = new Scanner(System.in);
public static int number(int max, int min) {
int teamchoice = 0;
for (boolean valid = false; valid == false;) {
teamchoice = in.nextInt();
if (teamchoice >= min && teamchoice <= max) {
valid = true;
} else {
System.out.println("Please enter a different value.");
}
}
return teamchoice;
}
public static boolean finished(boolean[] completedArray) {
int i = 0;
boolean done;
for (done = true; done == true;) {
if (completedArray[i++] == false) {
done = false;
}
}
return done;
}
public static void main(String[] args) {
int teamChoice = 0, gamesNum;
String[] sportteams = {"Basketball", "Football",
"Hockey", "Rugby",
"Soccer", "Volleyball"};
boolean[] completed = new boolean[sportteams.length];
int[][] Outcome = new int[64][sportteams.length];
for (boolean done = false; done == false;) {
for (int i = 0; i < sportteams.length; i++) {
System.out.print(i + 1 + " - " + sportteams[i]);
if (completed[i] == true) {
System.out.println(" - Finished");
} else {
System.out.println();
}
}
System.out.print("\nChoose a team from the list above:");
teamChoice = number(6, 1);
teamChoice--;
System.out.print("\nHow many games total did the " + sportteams[teamChoice]
+ " team play this season?: ");
gamesNum = in.nextInt();
System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
"1 - Win",
"2 - Tie",
"3 - Loss");
for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
System.out.print("\nEnter the outcome for game "
+ (wintieloss + 1) + ": ");
Outcome[wintieloss][teamChoice] = number(3, 1);
}
System.out.println("\n");
completed[teamChoice] = true;
done = finished(completed);
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.
for(int team = 0; team < sportteams.length; team++) { // for each team
System.out.println((team + 1) + " - " + sportteams[team]); // output the team
int game = 0; // index of the current game
while(Outcome[game][team] != 0) { // while there is data
System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
game++; // increment the index
}
System.out.println("Total games: " + game); // print the last index == total number of games
System.out.println();
}
I am trying to run a Java program to display 9 input boxes requesting names and examination scores and display on the message box the names and appropriate grades of each score. I tried doing something like this:
import javax.swing.JOptionPane;
public class StudentGrade {
public static void main(String[] args) {
String inputname;
String inputscore;
int number;
inputcourse = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputcourse) + " " + "D"); }
else if (number <50){
System.out.println((inputcourse) + " " + "C");}
else if (number <60){
System.out.println((inputcourse) + " " + "B");}
else System.out.println((inputcourse) + " " + "A");}
}
However, this can only run once. Please, how can I make it run nine times? Thanks.
Try this it'll work. In your code Check Inputname and InputCourse
or change inputCourse to inputName
import javax.swing.JOptionPane;
public class world {
public static void main(String[] args) {
String inputname;
String inputscore;
int number;
for(int i=0;i<9;i++){
inputname = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputname) + " " + "D");
}else if (number <50){
System.out.println((inputname) + " " + "C");
}else if (number <60){
System.out.println((inputname) + " " + "B");
}else {
System.out.println((inputname) + " " + "A");
}
}
}
}
To loop in control structure you can use a for, while loop, or a do-while loop. For a for-loop you should try:
public class StudentGrade{
public static void main(String[] args){
for (int i=0; i<9; i++){ repeat 9 times
// all the code you have in your main method now
}
}
}
For a while loop you should try:
public class StudentGrade{
public static void main(String[] args){
int i=0;
while (i++ < 9){ //repeat 9 times
// all the code you have in your main method now
}
}
}
For a do-while loop you should try:
public class StudentGrade{
public static void main(String[] args){
int i=1;
do{ //repeat 9 times
// all the code you have in your main method now
}while (i++ < 9);
}
}
Hope this helps.
put the code inside a for loop:
for(int i=0; i<9; i++){
inputcourse = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputcourse) + " " + "D");
} else if (number <50){
System.out.println((inputcourse) + " " + "C");
} else if (number <60){
System.out.println((inputcourse) + " " + "B");
} else {
System.out.println((inputcourse) + " " + "A");
}
}
I'm doing a coin toss program, and am trying to determine the longest possible run of heads or tails that were tossed. I already have code for determining if toss is heads or tails, but now need to count longest possible run. Help! Here's my code for the basic program.
public static void coin_toss(char [] toss)
{
int s = 0;
try
{
for (s = 0; s <= toss.length; s++)
{
double flip;
flip = (double)(Math.random());
if (flip < 0.5)
toss[s] = 't';
else
toss[s] = 'h';
}//end of for loop to load array
}
catch (ArrayIndexOutOfBoundsException errorMessage)
{
System.out.println("\nSubscript out of bounds");
System.out.println("Subscript went past the limit of " + toss.length);
System.out.println("Last value of subscript was --> " + s);
System.out.println("-------------------------------------------------");
System.out.println(errorMessage);
System.out.println("-------------------------------------------------");
}
}//end of toss coin
public static double percent_heads (char [] toss)
{
double percent_h;
int heads = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 'h')
heads = heads + 1;
}
System.out.println("There were " + heads + " heads results");
percent_h = (double)heads / toss.length;
return (percent_h);
}//end of heads percentage function
public static double percent_tails (char [] toss)
{
double percent_t;
int tails = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 't')
tails = tails + 1;
}
System.out.println("There were " + tails + " tails results");
percent_t = (double)tails / toss.length;
return (percent_t);
}//end of tails percentage function
public static void main(String [] args)
{
int num_toss = 0;
double heads, tails;
double percent_t, percent_h;
DecimalFormat percent = new DecimalFormat ("#0.00%");
System.out.print("How many tosses would you like? --> ");
num_toss = GetInput.readLineInt();
char [] toss = new char[num_toss];
System.out.println("You chose " + toss.length + " tosses");
coin_toss(toss);
heads = percent_heads(toss);
tails = percent_tails(toss);
System.out.println("The percentage of heads was --> " + percent.format(heads));
System.out.println("The percentage of tails was --> " + percent.format(tails));
longest_toss(toss);
java.util.Date today = new java.util.Date();
System.out.println("\nProgram terminated at " + today);
System.exit(0);
}//end of main method
}//end of class
There is a method I came up with.
public static void longest_toss(char[] toss){
int longestrun = 0;
int curlongestrun = 0;
char prevrun = toss[0];
for (int s = 1; s < toss.length; s++)
{
if (toss[s] == prevrun) {
curlongestrun++;
}else {
curlongestrun=0;
}
if(curlongestrun>longestrun){
longestrun = curlongestrun;
}
prevrun = toss[s];
}
System.out.println("Longest run is : " + longestrun + " Coin side : " + prevrun);
}
You can get maximum index of the array toss[] as Integer.MAX_VALUE - 8
Here it is less by 8 because, in the source code of java.util.ArrayList class, it is clearly mentioned that, MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 provided you have sufficient memory to hold the content of array with this much data.
int getLongestHeads(char [] toss){
int longestHeads = 0;
for(char c : toss)
{
if(longestHeads > 0 && c == 'h'){
longestHeads = longestHeads + 1;
}
else{
longestHeads = 0;
}
if(c == 'h' && longestHeads == 0) {
longestHeads = 1;
}
}
return longestHeads;
}