public static void main(String []args){
Random gen = new Random();
int[] numbers = new int[6];
int sum, product;
for (int i = 1; i < numbers.length; i++){
int pick = gen.nextInt(10);
numbers[i] = pick;
sum = (numbers[1]+numbers[2]+numbers[3]+numbers[4]+numbers[5]);
product = sum *2;
System.out.println("Random number: " + numbers[i]);
System.out.println("Product is: " + product);
}
}
It prints this:
Random number: 0
Product is: 0
Random numbers: 8
Product is: 16
Random number is: 9
Product is: 34
Random number is: 3
Product is 40
Random number is: 9
Product is 58
Which is fine, but I only want the total number, being 58. Something Simple :/ I'm new at this.
When ever you iterate through the loop you're invoking the System.out.println method, that's why you're getting all the output, you need to take the methods out of your for loop
Delete these:
System.out.println("Random number: " + numbers[i]);
System.out.println("Product is: " + product);
Put this one outside the for loop:
System.out.println("Product is: " + product);
Remove the following statements from the loop:
System.out.println("Random number: " + numbers[i]);
System.out.println("Product is: " + product);
And add the following outside the loop:
System.out.println("Product is: " + product);
Get this System.out.println("Product is: " + product); out of your loop
Related
So I have this code
int results[] = new int[13];
results[0]=19;
results[1]=22;
results[2]=21;
results[3]=25;
results[4]=32;
results[5]=38;
results[6]=16;
results[7]=31;
results[8]=30;
results[9]=26;
results[10]=19;
results[11]=17;
results[12]=23;
for(int i=0;i<results.length;i++)
System.out.println(results[lenght,Integer.MIN_VALUE,Integer.MAX_VALUE]);
}
}
How do I print the lenght of the array, the min value and the max malue all in a same array?
List<Integer>results2=new ArrayList<>();
for (int result : results) {
results2.add(result);
}
System.out.println("Minimum: " + Collections.min(results2));
System.out.println("Maximum: " + Collections.max(results2));
System.out.println("Amount of elements: " + results2.size());
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
String[] array2 = new String [10]; // New array that saves up to 10 elements(treatments)
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
int n = array.length;
for (int i=0; i<n; i++) {
for (int j=0; i<n ; j++) {
System.out.println();
treatment = input.nextInt();
if (treatment==1) {
cost += Integer.parseInt(array[i][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==2) {
cost += Integer.parseInt(array[i+1][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==3) {
cost += Integer.parseInt(array[i+2][1]);
System.out.print("Total cost so far: " + cost);
}
}
}
How do I move on from here? I figured that I have to store the input in the new array and exit the loop after 10 treatments or add an option to the user to print out the receipt when they're done.
The receipt needs to print all the chosen treatments along with the cost for each individual treatment. I will also need to add a variable to add a total amount for all the chosen treatments.
Here it is what you are trying to do, As the treatments are fixed so you can just index them as 0, 1, 2. One thing you can do is to make a hashmap in which you can store the treatment name and its cost (String,int) every time the user wants to enter.
Look at the code below
import java.util.*;
import java.util.HashMap;
public class treatment {
public static void main(String []args) {
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
// New array that saves up to 10 elements(treatments)
HashMap<String, Integer> treat = new HashMap<String, Integer>();
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
int n = array.length;
int i =0;
char c = '\0';
do {
System.out.println("\n\nControl" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
System.out.println("Exit: " + "-1");
System.out.println();
System.out.print("Enter treatment value (1, 2, 3): ");
treatment = input.nextInt();
if (treatment==1){
i = 0;
cost += Integer.parseInt(array[0][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==2) {
i = 1;
cost += Integer.parseInt(array[1][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==3) {
i = 2;
cost += Integer.parseInt(array[2][1]);
System.out.println("\nTotal cost so far: " + cost);
}
treat.put(array[i][0], cost);
} while (treatment != -1);
System.out.println("Total COst is : " + cost);
System.out.println("The treatements you opt for are:\n");
System.out.println(treat);
System.out.println("\n");
}
}
Here is my main method, I won't include all the rest of the code as it is not necessary. However, I am trying to figure out how to print out the highest score out of the three variables: player1, player2, player3
public static void main(String[] args) {
System.out.println("Welcome to Price is Right!");
System.out.println("Player 1 are you ready to spin?");
int player1 = player();
System.out.println("Player 1 Your final score is: " + player1);
System.out.println("Player 2 are you ready to spin?");
int player2 = player();
System.out.println("Player 2 Your final score is: " + player2);
System.out.println("Player 3 are you ready to spin?");
int player3 = player();
System.out.println("Player 3 Your final score is: " + player3);
// todo..
}
Any ideas would be appreciated. I have thought about calling in a method to calculate this or using if statements, I am not sure what is the best approach.
Same as my other answer, but much simpler, using an int[] array. We store the maxScore and the corresponding maxUser as we go, so we can output them at the end:
public static void main(String[] args) {
System.out.println("Welcome to Price is Right!");
int[] scores = new int[3];
int maxScore = -1;
int maxUser = 0;
for (int i = 0; i < scores.length; i++) {
System.out.println("Player " + (i+1) + " are you ready to spin?");
scores[i] = player();
if (scores[i] > maxScore) {
maxUser = i;
maxScore = scores[i];
}
System.out.println("Player " + (i+1) + " Your final score is: " + scores[i]);
}
System.out.println("Player " + (maxUser+1) + " won with a final score of " + maxScore);
}
you can put all player's scores in an array and then find highest amongst them
List<Integer> scores = new ArrayList<>();
scores.put(player1.getScore());
scores.put(player2.getScore());
int highest = Collections.max(arrayList);
System.out.println("Highest score is: " + highest);
OR you can simply do it via IF-Else
The easiest way I can think of is using if and else statements:
if(Player1> Player2 && Playe1 > Player3){
System.out.println("Highest score was earned by Player 1 which is"+ player1);
}else if(Player2> Player3 && Playe2 > Player1){
System.out.println("Highest score was earned by Player 2 which is"+ player2);
}else{
System.out.println("Highest score was earned by Player 3 which is"+ player3);
}
How about this very compact and easily extendable solution? Your teacher would be proud! If it is too complex take a look at my other solution, which only uses an int[]
public static void main(String[] args) {
System.out.println("Welcome to Price is Right!");
int playerCount = 3;
List<Integer> scores = new LinkedList<>();
for (int i = 0; i < playerCount; i++) {
System.out.println("Player " + (i+1) + " are you ready to spin?");
scores.add(player());
System.out.println("Player " + (i+1) + " Your final score is: " + scores.get(scores.size()-1));
}
System.out.println("The maximum score is " + Collections.max(scores));
}
Instead of storing each player score in its own variable, we just collect them all in a Collection. By doing it this way we can simply change playerCount to accommodate any number of players!
And if you want to print which player won you can replace the last line with this:
int maxScore = Collections.max(scores);
for (int i = 0; i < scores.size(); i++) {
if (scores.get(i) == maxScore) {
System.out.println("Player " + (i+1) + " won with a final score of " + maxScore);
break;
}
}
Or if you want to be (very) fancy:
OptionalInt maxVal = IntStream.range(0, playerCount).reduce((a, b) -> scores.get(a) > scores.get(b) ? a : b);
maxVal.ifPresent(i -> System.out.println("player " + (i+1) + " won with a final score of " + scores.get(i)));
Considering result is your custom object it's contain marks.
First create object of comparator class like
Comparator com= comparator.comparing(Result::getMarks);
Here getMarks is your getter method and mark is your variable.
Result result = List.s stream(). Max(com).get();
You can also find minimum value using min function..
I have a homework assignment and the program generates a random number of students taking a random number of tests. The user must enter the students names and test scores. Once that is done the program will print on the screen : STUDENT REPORT Scores for Fred:
Test #1: 78
Test #2: 80
Average for Fred: 79.0
Scores for Sue:
Test #1: 91
Test #2: 94
Average for Sue: 92.5
... and so on depending on what number of students and tests you get.
I get everything right up until the average part how can I fix it?
Here's my code:
public static void populateNames(String[] names)
{
for(int i = 0; i<names.length; i++)
{
out.print("Enter student " + (i+1) + " name: ");
names[i] = keyboard.next();
}
}
// Code your 3 methods below...
//Ask the user for the student name as well as the test scores
public static void populateTestScores(String[] names, int[][] scores)
{
out.println();
for(int i=0; i<names.length; i++)
{
out.println();
out.println("Entering scores for: " + names[i]);
for(int s=0; s<scores[0].length; s++)
{
out.print("Enter score for test #" + (s+1) + ": ");
scores[i][s] = keyboard.nextInt();
}
}
out.println();
}
//Print each studdent test scores and ther average
public static void printStudentReport(String[] names, int[][] scores)
{
out.println("STUDENT REPORT");
for(int i=0; i<names.length; i++)
{
out.print("Scores for " + names[i] + ": ");
out.println();
for(int s=0; s<scores[0].length; s++)
{
out.println("Test #" + (s + 1) + ": " + scores[i][s]);
}
out.println();
int s=0;
if(s<scores[0].length)
{
s++;
double sum = 0;
sum += scores[i][s];
double average = sum / scores[0].length;
out.println("Average for " + names[i] + ": " + average);
out.println();
}
}
out.println();
}
The problem is in the way you're computing sum in printStudentReport: it only contains the second element in the list of scores because you're creating and adding to sum after the for loop (instead of creating before the loop and adding in it).
I'd rearrange that method to (reformatted for compactness):
// Print each studdent test scores and ther average
public static void printStudentReport(String[] names, int[][] scores) {
out.println("STUDENT REPORT");
for (int i = 0; i < names.length; i++) {
out.print("Scores for " + names[i] + ": ");
out.println();
double sum = 0;
for (int s = 0; s < scores[0].length; s++) {
out.println("Test #" + (s + 1) + ": " + scores[i][s]);
sum += scores[i][s];
}
out.println();
if (0 < scores[0].length) {
double average = sum / scores[0].length;
out.println("Average for " + names[i] + ": " + average);
out.println();
}
}
out.println();
}
I have these 4 sentences that are printed and basically want the user to input a score for each sentence out of 10 and store them in array and then include a way of sorting the sentences in order of the scores given to them and print them in the order of highest to lowest
I am new to java, and I am struggling how to go about this problem, I managed to write some code below and thats the furthest ive got. I don't know how to store those printed messages in the array. And i'm not sure how to link the scores with the messages that gets printed. Can someone help, :/
public static void arrays()
{
String []noun = {"face", "eyes", "nose", "lips", "ears", "cheeks"}; //stores all the arrays for noun words
Random random = new Random(); //to work out the new random
int rand1 = random.nextInt(noun.length);
String []verb = {"enchant", "dazzle", "captivate" , "lure", "desire", "entice" }; // stores all the arrays for verb words
Random random2 = new Random();
int rand2 = random2.nextInt(verb.length);
String []adjective = { "alluring", "angelic", "adoring", "appealing", "attractive", "beautiful"}; // stores all the arrays for adjectives
Random random3 = new Random();
int rand3 = random3.nextInt(adjective.length);
printmessage (noun[rand1], verb[rand2], adjective[rand3]); //to print the message that will use the arguments from the random selected words.
getscore ();
}
public static void printmessage(String noun, String verb, String adjective) //calls the arguments defined above, which will be used below, when executing the messages.
{
System.out.println("line 1: I would love to " + verb + " your " + adjective + " " + noun + "\n");
System.out.println("line 2: Your are my " + adjective+ " " + noun + " .You " + verb + " me" + "\n");
System.out.println("line 3: you always look great in that " + adjective + " dress" + " and you " + verb + " me with your " + noun + "\n");
System.out.println("line 4: I get butterflies when I see your " + noun + " , you make me want to " + verb + " , in your " + adjective + " world" + "\n");
}
public static void getscore()
{
Scanner input = new Scanner(System.in);
for (int i=0; i<=3; i++)
{
JOptionPane.showInputDialog("Enter the scores for line: " + i);
int result = input.nextInt();
int[] scores = new int[result];
scores[i] = input.nextInt();
}
}
Reverse the call of getScore and print statement as you need score before to print the message. So you could return int array with getScore back to main method like:
public static int[] getscore() {
int[] scores = new int[3];
//your logic to populate scores
return scores;
}
Then in your main you use:
int count = 0;
int scores [] = getscore ();
Arrays.sort(scores);
printmessage (noun[rand1], verb[rand2], adjective[rand3], score[count++]); //to print the message that will use the arguments from the random selected words.
And in your print message you could use if like below:
switch(score) {
case 1://blah blah
break;
//and so on
}