I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.
Related
This method is to sum up all the numbers present on the dice and add them to the total score. There are 5 dice, I'm having trouble with it because whenever I activate it through the GUI it just adds some random numbers together and not the numbers present, also I can activate the button without rolling and it gives me numbers still.
dieList is the ArrayList that carries the current die numbers, and nextRound just puts the game to the next round. If you require more information I will be happy to supply it.
public void checkChance(){
int chance = 0;
for(GVdie die: dieList){
chance = chance + die.getValue();
score = score + chance;
}
nextRound();
}
I have a school assignment that I finished most of, but I can't figure out how to read from a text file, and I'm having a certain problem regarding the code, The task I was given is:
"Write a program to read an input file named “input.txt”. The file
consists of several graphs. Each graph starts with a line containing
the number of vertices n, where 1 < n < 200. Each vertex is labeled by
a number from 0 to n-1. The second line contains the number of edges
l. After this, l lines follow each containing two vertex numbers
representing an edge. An input with n = 0 marks the end of the input
and is not to be processed.
You have to choose an appropriate data structure to represent the
graph. Indicate whether its Complete/has a self loop/ has an isolated
vertex "
Sample Input:
4
5
0 1
2 0
0 3
1 2
2 3
3
3
0 1
1 2
2 0
0
Sample output:
Not Complete/No Self-Loop/No Isolated Vertex
Complete/No Self-Loop/No Isolated Vertex
I used adjacency matrix, I wrote code that reads the edges, decided whether it has a self loop and whether there's an isolated vertex.
1- I wrote a code for finding whether it's complete or not, but it doesn't behave the way I want it, it always shows that It's not complete.
2- I am not familiar with the way to read inputs from a text file, so please I need help.
The part where I have to make it read any amount of matrices, is kinda easy (but leaving a hint for it is always welcomed hehe), but I just wanna make sure I know how to do the two steps above before I do it, I'd really appreciate leaving comments so I could learn whatever step you help me with, anyway, this is the program:
package phase1project;
import java.util.Scanner;
public class Phase1Project {
public static void main(String[] args) {
int max = 2000; //declare the max element for the array
int[][] adj= new int[max][max]; //declare the array
int n; //nodes
int l; // to determine the max number of edges
int loopChecker = 0;//To check whether there's a loop or not
int isolatedCounter = 0;
int completeCounter = 0;
int subCounter = 0;
int origin; //to determine where the edge starts
int destination; //to detemine where the edge stops
int i,j; //for the loop
Scanner input = new Scanner(System.in); //to scan inputs
System.out.println("Enter the number of vertices: ");
n=input.nextInt();
while(n<1 || n>200){ //nodes/vertices should be between 1 and 200
System.out.println("\nWrong input! Insert a numbe between 1 and 200\n");
n=input.nextInt();
}
System.out.println("Enter the number of edges: ");
l=input.nextInt();
System.out.println("Enter the begining of the edge then press enter then enter the end side of the edge to input it correctly.\n");
for(i=0;i<=(l-1);i++){ //a loop that populates the adjacency matrix
System.out.println("Enter edge "+i+": >> (0 0) to quit: ");
origin = input.nextInt();
destination = input.nextInt();
adj[origin][destination]=1;
}
System.out.println("\n\n\nThis is how your graph looks like:\n");
for(i=0;i<=(n-1);i++){
for(j=0;j<=(n-1);j++)
System.out.printf("%4d",adj[i][j]);
System.out.printf("\n");
}
//////////////////////////////////////////////////////////////
//Loop Checker starts from here
for(i=0;i<=(n-1);i++){
if(adj[i][i]==1){//If there's a 1 in the same place
loopChecker=1;
break;
}
}
if(loopChecker==1){
System.out.println("Self Loop");
}
else{
System.out.println("No Self Loop");
}
//Loop Checker ends here
///////////////////////////////////////////////////////////////
//checks whether the graph is complete
for(i=0;i<=(n-1);i++){
subCounter=0;//reset
for(j=0;j<=(n-1);j++){
if(adj[i][j]==1){
subCounter+=1;//buffer variable
}
if(subCounter==(n-1)){
completeCounter+=1;//this counter incriments if the whole line has 1s that equal n-1
}
}
}
if(completeCounter == n){
System.out.println("Complete");
}
else
System.out.println("Not Complete");
//end of complete or not check
/////////////////////////////////////////////////////////////////////
subCounter =0;//reset
//checks whether the graph has an isolated vertex or not
for(i=0;i<=(n-1);i++){
for(j=0;j<=(n-1);j++){
if(adj[i][j]==0){
subCounter+=1;//buffer variable
}
if(subCounter==n){
isolatedCounter=1;
break;
}
}
subCounter=0;//reset
}
if(isolatedCounter==1){
System.out.println("There's an isolated vertex");
}
else
System.out.println("There's no isolated vertex");
//end of isolated check
///////////////////////////////////////////////////////////////////
}
}
I hope I'm not breaking any rule by posting this, if I did please tell me.
Thanks in advance ;)
I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());
The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.
You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.
As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!
This is my first question to this site so I apologize and would appreciate feedback if I post something incorrectly! This is a homework question although I don't seem to be able to tag it that way.
Anyways, the code appears to compile fine (using BlueJ) but gets stuck when it enters the first while loop when I run it. I added some output lines to see where the problem occurs and the first System.out when it enters the first while loop never happens... The JVM just continues working until I force it to reset. I believe my initial while loop should run 4 times then exit with the values I have used (5 students, i starts at 2), but it doesn't appear to do anything at all and I'm at a loss as to what I've done wrong.
Summary of what the program is intended to do when completed.
A series of students walk by a row of lockers.
Student 1 opens all the lockers
Student 2 closes every second locker
Student 3 reverses the state of every third locker, etc. for the number of students
I am aware I haven't set the boolean locker flag to flip properly yet and intend to use a variation of !myBool to do so within the second while loop - but first I want to ensure my while loops work at all. Hoping I'm missing something simple due to staring at it for too long!
import java.util.Arrays;
public class Lockers
{
public static void main (String[]args)
{
// Size of lockerArray
int arraySize = 5;
// Set up new lockerArray
boolean[] lockerArray = new boolean[arraySize];
// Variable for number of students in the exercise
int studentNumber = 5;
System.out.println("Student 1 opens all the lockers.\n");// Outputs, good
// Student 1 opens all the lockers
// Boolean values for lockerArray true = OPEN; false = CLOSED
Arrays.fill(lockerArray, true);
System.out.println(Arrays.toString(lockerArray)); // Outputs 5 true, good
// Set the student counter at 2 (Student 1 has already made their pass)
int i = 2;
// Loop until you run out of students
while (i <= studentNumber);
{
System.out.println("Student Number " + i + " is making their pass.\n");// NEVER HAPPENS - have to reset JVM to stop program
// Set up a variable to control the sequence required (i.e., Student 2 every second locker,
// Student 3 every third locker, etc.
int j = i;
while (j <= arraySize);
{
System.out.println("Student is changing the status of locker number " + j + ".\n");
// Reverse the flag at each locker for which the statement is true for this student number
// Need to reduce the variable by 1 as locker 1 would be sitting in lockerArray[0] position
lockerArray[j-1] = false;
// Increment locker number by the value of the student in the sequence
j = j + i;
}
// Increment the student count
i++;
}
// Print the final array status
System.out.println(Arrays.toString(lockerArray));
}
}
Your while loops have semi-colons after them.
while (i <= studentNumber);
This is causing the infinite loop, since your i variable can't change.
You need brackets around your while loop unless it will run infinitely
Try This:
while (i <= studentNumber){
// action
}