Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}
Related
I need the answer to display the lowest score and highest whilst also giving the correct subject to go along with it
import java.util.Scanner; //import package
class Task11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); //import scanner
System.out.print("Enter SAC score for Financial: "); //enter for 3 subject sac scores
int financial = in.nextInt();
System.out.print("Enter SAC score for Statistics: ");
int stats = in.nextInt();
System.out.print("Enter SAC score for Networks: ");
int network = in.nextInt();
double average = (financial+stats+network)/3; //calculate average, use double incase of decimals
if (financial > stats) { //determine if number1 is bigger than 2 then equal itself
int answer = financial;
financial = stats;
stats = answer;
}
else if (stats > network) { //same for 2 and 3
int answer = stats;
stats = network;
network = answer;
}
else if (financial > stats) { //let it repeat itself
int answer = financial;
financial = stats;
stats = answer;
}
int highest = network;
int lowest = financial;
System.out.println("The average is: " + average);
System.out.println("The highest score was: " + highest);
System.out.println("The lowest score was: " + lowest); //show user results of input
}
}
This is not good-code but it can show subject in case same score:
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // import scanner
Map<Integer, List<String>> subjectScores = new HashMap<Integer, List<String>>();
List<String> subjects = new ArrayList<String>();
System.out.print("Enter SAC score for Financial: "); // enter for 3
// subject sac
// scores
List<Integer> scores = new ArrayList<Integer>();
int financial = in.nextInt();
subjects = new ArrayList<String>();
subjects.add("Financial");
subjectScores.put(financial, subjects);
scores.add(financial);
System.out.print("Enter SAC score for Statistics: ");
int stats = in.nextInt();
if (subjectScores.containsKey(stats)) { // check if score of Statistics same with score of Financial
subjects = subjectScores.get(stats);
subjects.add("Statistics");
} else {
subjectScores.put(stats, Arrays.asList("Statistics"));
}
scores.add(stats);
System.out.print("Enter SAC score for Networks: ");
int network = in.nextInt();
if (subjectScores.containsKey(network)) {
subjectScores.get(network).add("Networks");
} else {
subjects = new ArrayList<String>();
subjects.add("Networks");
subjectScores.put(network, subjects);
}
scores.add(network);
System.out.println(
"The average score was: " + (financial + stats + network) / 3);
int highestScore = Collections.max(scores);
int lowestScore = Collections.min(scores);
System.out.print("The highest subject was ");
for (String subject : subjectScores.get(highestScore)) {
System.out.print(subject + ", score: " + highestScore + ". ");
}
System.out.println();
System.out.print("The lowest subject was ");
for (String subject : subjectScores.get(lowestScore)) {
System.out.print(subject + ", score: " + lowestScore + ". ");
}
System.out.println();
in.close();
}
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
for(int j = 0; j<arrayOfNames.length;j++)
{
System.out.print("\nEnter the income of friend " + (j+1) + " : ");
income[j] = scan.nextLong();
}
}
}
}
This is my code, I want to take input name from user then the income of that person then again the name of another person
The above code is not arranged properly, I think there's problem in the for loop the sample output should be like:
Enter how many friends: 2
Enter name of friend 1 : #############
Enter income of friend 1 : ##############
Enter name of friend 2 : #############
Enter income of friend 2 : ##############
You should take inner for loop out.
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
for(int j = 0; j<arrayOfNames.length;j++)
{
System.out.print("\nEnter the income of friend " + (j+1) + " : ");
income[j] = scan.nextLong();
}
scan.close();
}
}
Besides, if you want to enter them in order, you should just use one for loop
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
System.out.print("\nEnter the income of friend " + (i+1) + " : ");
income[i] = scan.nextLong();
scan.nextLine();
}
scan.close();
}
}
As a side note, don't forget to close() scanner after its task is completed.
I need to create a random poem generator while using arrays and input from the user (the user needs to input a minimal of 3 adjectives and 3 nouns) then the program has to randomly combine an adjective with a noun (a noun and an adjective can not be re-used twice) and display it. There needs to be 3 lines in the poem. Here's my code but it doesn't function at all the way it's supposed to! Please tell me what i did wrong!
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2, adj;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
if (x >= 3){
String[] noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
String[] adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
poemline[0] = adj + noun2;
poemline[1] = adj + noun2;
poemline[2] = adj + noun2;
System.out.println(poemline[0]);
System.out.println("/t/t" + poemline[1]);
System.out.println("/t/t/t/t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}
Try this
import java.util.Random;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2 = null;
String adj = null;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
String[] noun = null;
String[] adjective = null;
if (x >= 3){
noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
Random rnd = new Random();
poemline[0] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[1] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[2] = adjective[rnd.nextInt(y-1)] +" " +noun[rnd.nextInt(x-1)];
System.out.println(poemline[0]);
System.out.println("\t\t" + poemline[1]);
System.out.println("\t\t\t\t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}
I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}