Java Change Prompt Order - java

I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}

Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.

Related

How to update data in array with user input values with java?

I am trying to create a garage with three floors and three lots on each floor. I am fairly new to java, so I am really having trouble with this. I want to ask the user if they are leaving (0) or parking (1), then which floor they were on or want to be on, and which lot they were in or want to be in. Then I want to use that data and update the array to show Reserved for that spot. But what I have isn't working. Any help would be appreciated.
import java.util.Scanner;
public class Parking {
public static void main(String[] args) {
String parkingspace[][] = new String[3][3];
for(int floor=0; floor<parkingspace[0].length; floor++) {
for(int lot=0; lot<parkingspace[floor].length; lot++) {
parkingspace[floor][lot]="Empty";
}
}
Scanner scan = new Scanner(System.in);
while(true){
for(int floor=0; floor<parkingspace[0].length; floor++) {
for(int lot=0; lot<parkingspace[floor].length; lot++) {
parkingspace[floor][lot]="Empty";
System.out.print("Floor "+floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
System.out.println();
}
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
if(input==1) {
if(parkingspace[floor][lot].equals("Empty")) {
if(input==1) {
parkingspace[floor][lot]="Reserved";
System.out.print("Floor "+ floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
}else if(input==0){
parkingspace[floor][lot]="Empty";
System.out.print("Floor "+ floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
}
}
}
You are close. You need to delete the part where you reset all the parking spaces. Also, you probably don't need to print anything after the user has input their choice.
For extra credit, you need to add error checking. What if the user enters space #12345? Or "Hello"? You should handle these cases.
Here's your code, slightly modified:
public static void main(String[]args) {
String parkingspace[][] = new String[3][3];
// Make these variables to be consistent
final String empty = "EMPTY";
final String reserved = "RSRVD";
// Initialize
for (int floor = 0; floor < parkingspace.length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = empty;
}
}
Scanner scan = new Scanner(System.in);
while (true) {
// Print the parking lot
for (int floor = 0; floor < parkingspace.length; floor++) {
System.out.print("Floor " + floor + ": ");
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
System.out.print("Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
System.out.println();
}
// Get user input
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
// Update parking lot
if (input == 1 && parkingspace[floor][lot].equals(empty)) {
parkingspace[floor][lot] = reserved;
}
else if (input == 0 && parkingspace[floor][lot].equals(reserved)) {
parkingspace[floor][lot] = empty;
}
}
}
You have a redundant if(input == 1) check. It could just be:
if (input == 1 && parkingSpace[floor][lot].equals("Empty")) {
parkingSpace[floor][lot] = "Reserved";
}
Also, your code works for me. I did have to add several brackets to close off methods and the class, though.
import java.util.Scanner;
public class Parking {
public static void main(String[] args) {
String parkingspace[][] = new String[3][3];
for (int floor = 0; floor < parkingspace[0].length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = "Empty";
}
}
Scanner scan = new Scanner(System.in);
while (true) {
for (int floor = 0; floor < parkingspace[0].length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = "Empty";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
System.out.println();
}
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
if (input == 1) {
if (parkingspace[floor][lot].equals("Empty")) {
if (input == 1) {
parkingspace[floor][lot] = "Reserved";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
} else if (input == 0) {
parkingspace[floor][lot] = "Empty";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
}
}
}
}

I want to print how many number is greater than the average

I already print the total and average. However I can't print how many numbers is greater than average.
I think the problem is the number>= average, it seems like only adding the last input.
public static void main(String[] args) {
int i;
int number = 0;
double total=0;
double average=0;
int aboveaverage=0;
Scanner read = new Scanner (System.in);
for(i=1;i<9;i++){
System.out.print("Enter number " + i +": ");
number=read.nextInt();
if(number<0){
System.out.println("Invalid Input");
break;
}
total+=number;
}
if(number>=average){
aboveaverage+=1;
System.out.println("Greater than average is :" + aboveaverage);
}
average=total/8;
System.out.println("Print total : "+ total);
System.out.println("Print Average : " +average );
}
}
You will need to collect all numbers (by placing them in an int array), and iterate over all numbers, for example inside a for loop.
public static void main(String[] args) {
int i;
int number = 0;
int numberCount = 8;
int[] numberArray = new int[numberCount];
double total = 0;
double average = 0;
int aboveAverage = 0;
Scanner read = new Scanner (System.in);
for(i = 0; i < numberCount; i++){
System.out.print("Enter number " + (i + 1) + ": ");
number = read.nextInt();
if(number < 0){
System.out.println("Invalid input");
continue;
}
numberArray[i] = number;
total += number;
}
average = total / numberCount;
for(i = 0; i < numberCount; i++){
if(numberArray[i] > average) {
aboveAverage++;
}
}
System.out.println("Count of numbers greater than average: " + aboveAverage);
System.out.println("Print total: " + total);
System.out.println("Print average: " + average);
}

Problem with keeping score with a while loop (Java)

I am in an intro to the java class, and for one of my assignments, I have to use a loop (for or while) to keep track of scores between myself and the computer.
Here is the exact word for word instructions from my professor:
Write a program that does this: You (as a programmer) are the dealer.
pick a random number for yourself (between 0 - 100). Ask the user to input a random number (between 0 - 100) Whoever is closer to 21 wins the game.
(part 2) -Loop (keeping a counter) rite the same program and keep it going so that it keeps playing (dealing hands and saying who wins) until the user enters 21 at which point you print out some stats and say goodbye. For example, your goodbye might look like this:
Number of rounds played: 5
Dealer won: 3
Player won:2
you're 2 for 5.
Now I have written the code and played around it for hours and hours, and cannot make it work with a loop. I've tried while, do while, and for. I have looked everywhere on the internet for similar examples but cannot make a loop work in my program whatsoever. If anyone has any suggestions I would sure appreciate the feedback.
my code:
import java.util.*;
class asd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
System.out.println("computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("the winner is the user!" + input);
dealerscore++;
gamesplayed++;
} else {
System.out.println("the winner is the computer!" + r);
userscore++;
gamesplayed++;
}
if (input == c) {
System.out.println("thank you for playing. you won.");
}
if (r == c) {
System.out.println("Thank you for playing:" + userscore);
System.out.println(userscore);
}
if (input == 0) {
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
while (input != c && r != c)
gamesplayed++;
}
// TODO code application logic here
}
Everything works fine, but I can't get the loop to work anywhere here.
You need a while loop that contains your game logic. The condition should just check if the input != c.
Then inside the loop, keep asking the user for input. Also, you mixed up userscore and dealerscore when adding the score.
Then at the end, once you come out of the loop, you can print the scores/stats.
Please read the comments below:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!: ");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
/*
This loop runs the game until the user enters 21
*/
while (input != c) {
System.out.println("Computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user! " + input);
userscore++; //You mixed up userscore and dealerscore
} else {
System.out.println("The winner is the computer! " + r);
dealerscore++; //You mixed up userscore and dealerscore
}
/*
User needs to keep entering guesses
*/
System.out.println();
System.out.println("Enter another guess: ");
r = rand.nextInt(max - min) + min;
input = sc.nextInt();
}
/*
You don't need any conditions since the games have already ended
But it should be outside and after the loop
*/
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
}
Change the loop with
while (input != c && r != c){
gamesplayed++;
System.out.println("Games played: " + gamesplayed );
}
you will see it is working. I would format the code better to debug it easier and always use the brackets.
Try this. Just refer to the code for explanations.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
System.out.println("");
int min = 0;
int max = 100;
int input;
int c = 21;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 1;
Random rand = new Random();
while (true) { // so that the game will keep playing
System.out.println("----------------- ROUND " + gamesplayed + " -----------------");
int r = rand.nextInt(max - min) + min; // computer's choice
while (true) { // so that it will keep asking the user in case the user enters an invalid input
try {
System.out.print("Enter a random number! :");
input = Integer.parseInt(sc.nextLine());
break;
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
System.out.println("The computer's random number is " + r);
// checking for the rounds winner
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user!");
userscore++;
} else {
System.out.println("The winner is the computer!");
dealerscore++;
}
if (input == c) { // checking for ending the game
System.out.println("================ GAME STATS ================");
System.out.println("Thank you for playing.");
System.out.println("Number of hands played: " + gamesplayed);
System.out.println("Dealer score: " + dealerscore);
System.out.println("User score: " + userscore);
System.out.println("You are " + userscore + " out of " + gamesplayed + "!");
System.out.println("============================================");
sc.close();
break;
}
gamesplayed++; // increment games played
System.out.println("--------------------------------------------");
}
}
}

How to set a limit in a for loop?

I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!

How do I create a counter to count the number of people who had the maximum salary entered?

import java.util.Scanner;
public class Lab4a{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int numemployees, max, freq;
System.out.print("Enter number of employees: ");
numemployees = keyboard.nextInt();
System.out.println("Enter salary for " + numemployees + " employees:");
int[] salaries = new int [numemployees];
max = salaries[0];
for (int i=0; i < salaries.length; i++){
salaries[i] = keyboard.nextInt();
if (salaries[i] > max)
max = salaries[i];
}
System.out.println("Maximum salary is " + max);
System.out.println(" employees received " + max);
}
So the output for this would be
Enter number of employees: 3
Enter salary for 3 employees:
10000
15000
15000
Maximum salary is 15000
employees received 15000
I WANT IT TO SAY, "2 employees received 15000". That's all I need for it to do. Please help me how to establish that counter using another loop... as simple as possible! Thanks!
Amend your loop like this:
max = salaries[0];
freq = 1;
for (int i=0; i < salaries.length; i++){
salaries[i] = keyboard.nextInt();
if (salaries[i] > max) {
freq = 1;
max = salaries[i];
} else if (salaries[i] == max) {
++freq;
}
}
System.out.println(freq + " employees received " + max);
int count = 0;
for (int i=0; i < salaries.length; i++){
if (salaries[i] == max)
count++;
}
System.out.println(count+" employees received "+max);
Try this out
int count =0;
System.out.println("Maximum salary is " + max);
System.out.println(" employees received " + max);
for(int i=0;i< salaries.length ;i++)
{
if(salaries[i] == max)
count++;
}
if(count>1)
{
System.out.println(count+" employees received " + max);
}
Here you go -
package com.walmart.services;
import java.util.Scanner;
public class Lab4a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numemployees, max, freq = 0;
System.out.print("Enter number of employees: ");
numemployees = keyboard.nextInt();
System.out.println("Enter salary for " + numemployees + " employees:");
int[] salaries = new int[numemployees];
max = 0;
for (int i = 0; i < salaries.length; i++) {
salaries[i] = keyboard.nextInt();
if (salaries[i] > max) {
freq = 1;
max = salaries[i];
} else if (salaries[i] == max) {
freq++;
}
}
System.out.println("Maximum salary is " + max);
System.out.println(" employees received " + freq);
}
}

Categories

Resources