I am a college student and this is my first semester learning Java programming. For the past few days I've been stuck on some things when learning Java. One activity I'm stuck on for my class is this one:
Retype the statements, correcting the syntax errors.
System.out.println("Num: " + songnum);
System.out.println(int songNum);
System.out.println(songNum " songs");
Note: These activities may test code with different test values. This activity will perform two tests: the first with songNum = 5, the second with songNum = 9.
This is what I have so far:
import java.util.Scanner;
public class Errors {
public static void main (String [] args) {
int songNum;
songNum = 5;
System.out.println("Num: " + songNum);
System.out.println("5");
System.out.println("5 " + "songs");
The website we are using called Zybooks says the code above is correct for outputting:
Num: 5
5
5 songs
But I can't figure out what to do to output the same but with the number 9. I've tried doing the same 3 lines for it but it says it's not the correct way to do it. How do output both 5 and 9 for the values?
Change the 2nd and 3rd print statements to the following:
System.out.println(songNum);
System.out.println(songNum + " songs");
The problem was you hardcoded the value of 5 within a string making it impossible to change.
You cannot print the number nine with the code that you wrote. if you want to get the number nine then you have to change the code and create a new variable e.g. x = 9;
What you can do something like that:
import java.util.Scanner;
public class Errors {
public static void main (String [] args) {
int songNum;
songNum = 5;
x = 9;
System.out.println("Num: " + songNum);
System.out.println(songNum);
System.out.println(songNum + " songs");
System.out.println("Num: " + x);
System.out.println(x);
System.out.println(x+ " songs");
Your main issue is that you had cached your value (5) into a string, rendering it unchangeable.
Related
The number of calls received per minute at a Help Desk has been estimated to be between 5 and 10.
Write a simulation program that simulates calls arriving at the Help Desk for a period of 12 hours and output the frequency of calls during this period.
Sample output:
(Note: The frequencies for your program will be different from the ones shown below. Each time you run your program, you should get different frequencies)
Calls/Minute Frequency
5 155
6 172
7 148
8 123
9 62
10 60
This is what I've came up with, but cannot figure out how to split/leave a gap between calls/minute and frequency. Basically splitting it into two rows.
import java.util.Random;
public class randomCalls {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rn = new Random();
int n;
for(int i=1;i<=6;i++)
{
n = rn.nextInt(6) +5;
System.out.println("Calls/Minute" +"\n" + n);
System.out.print(' ');
System.out.println(" Frequency" + "\n"+ i);
}
}
}
I'm pretty sure you are trying to print out Calls/Minute and Frequency in columns. Here is a helpful link.
In order to use that method your need to...
Combine the lines System.out.println("Calls/Minute" +"\n" + n); and System.out.println(" Frequency" + "\n"+ i);, and format the resulting single line so that it is split into two columns.
//Example
System.out.printf("%-12.30s %-30.30s%n","Column 1","Column 2");
Place it BEFORE your for loop (or else it will print every time)
Within your for loop, format your output exactly the same as you did the line in step one.
//Example
System.out.printf("%-12.30s %-30.30s%n",n,i);
Sample output in your program would look like this:
Calls/Minute Frequency
6 1
7 2
8 3
8 4
9 5
6 6
Here is how I got it to print like described:
Random rn = new Random();
int n;
for(int i=1;i<=6;i++) {
n = rn.nextInt(6) +5;
System.out.println( n + " " + i );
Hope this helps!
Hey I'm writing a java class and the result has to be from this image
.
The whole program works great but in the end i don't get the correct math output. I think it some problem in my equation. Can someone help me with the problem. Thank you
import java.util.Scanner;
import java.awt.Toolkit;
public class Sports
{
public static void main(String[] args)
{
//create scanner object
Scanner input=new Scanner(System.in);
//create tolkit object
Toolkit tk=Toolkit.getDefaultToolkit();
int players;
int team=15;
System.out.println("SporT's Team Calculator");
System.out.println("=======================");
System.out.println("Enter the Total number of players===>");
players=input.nextInt();
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
players=input.nextInt();
while(players>15 || players<9 )
{
tk.beep();
System.out.println("\nInvalid number of players per team, please re-enter...");
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
players=input.nextInt();
players=players%team;
}
System.out.println("There will be " + players + " teams, "
+ "with " + players + " players " + "left over.");
System.out.println("\nThank you for using SporT's Software!");
}
}
You are saving both the total number of players and the number of players on a team into the same variable players. If you were to answer that the total number of players is 142 it'll immediately be overwritten by the next assignment to players for the number per team. These should be separate variables int playersPerTeam for instance
First, you are working with java so the variable
players
will constantly gets overridden.
To solve this, divide the variable
players
into 2 different variables, one to count the number of players(total) and another to count the number of players per team. This also means that you will need to change the part when you continuously ask the user for a valid input set (in the while loop) .
Secondly, your math in calculating your total number of teams and the players left over are incorrect. Below, I included a working version:
int numTeams = totalPlayers / playersPerTeam;
int playersLeft = totalPlayers - (playersPerTeam * numTeams);
System.out.println("There will be " + numTeams + " teams, " + "with " + playersLeft + " players " + "left over.");
It seems like you are retrieving two pieces of information: the total number of players and the players per team. So you will need two variables to store both pieces of information. Instead of overriding the same variable - losing the first piece of information collected.
The Equations:
To get the number of teams:
(int)(players / playerPerTeam)
To get the number of left over players:
players-playerPerTeam*totalTeams
Also I don't understand why you are getting two different numbers, 11 and 10, for the same variable, players in the console.
i actually already figured it out but thanks.
import java.util.Scanner;
import java.awt.Toolkit;
public class Sports
{
public static void main(String[] args)
{
//create scanner object
Scanner input=new Scanner(System.in);
//create tolkit object
Toolkit tk=Toolkit.getDefaultToolkit();
int players;
int team;
System.out.println("SporT's Team Calculator");
System.out.println("=======================");
System.out.println("Enter the Total number of players===>");
players=input.nextInt();
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
team=input.nextInt();
while(team>15 || team<9 )
{
tk.beep();
System.out.println("\nInvalid number of players per team, please re-enter...");
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
team=input.nextInt();
}
int result=players/team;
int player= players%team;
System.out.println("There will be " + result + " teams, "
+ "with " + player + " players" + " left over.");
System.out.println("\nThank you for using SporT's Software!");
}
}
I should Define four boolean variables as follows:
Freshman for students in levels 1 or 2.
Sophomore for students in levels between 3 and 5.
Junior for students in levels between 6 and 8.
Senior for students in levels 9 or 10.
the user enters the course code, then I decide which level is the student (user) and then define the 4 boolean variables depending on the level.
But I don't know how to do the equal() for two thing or more.
this is my code:
import java.util.*;
public class point8 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// declaring
String CourseCode, Level;
boolean Freshman, Sophomore, Junior, Senior;
// input
System.out.println("Course code:");
CourseCode = input.next().toUpperCase();
System.out.println("\nCourse Code: " + CourseCode);
// output
Level = CourseCode.substring(CourseCode.length() - 1);
System.out.println("Student Level: " + Level);
Freshman = Level.equals("1");
System.out.println("Freshman: " + Freshman);
Sophomore = Level.equals("3");
System.out.println("Sophomore: " + Sophomore);
Junior = Level.equals("6");
System.out.println("Junior: " + Junior);
Senior = Level.equals("9");
System.out.println("Senior: " + Senior);
}
}
What shall I do to compare from level 1 or 2 for freshman
and compare from level 3 to 5 for Sophomore ?
It seems to me that you're better of using integers, just parse the String to int.
For example:
int myLevel = Integer.parseInt(Level);
if(myLevel >= 3 && myLevel <= 5)
{
System.out.println("Sophomore: " + Sophomore);
}
You might get an error if the user inserts a letter instead of a number, to avoid this you need to catch the exception and handle it. This however is an entire different story, but you should readup about it: https://docs.oracle.com/javase/tutorial/essential/exceptions/
if(Level.equals("9") || Level.equals("10"))
{
//Senior
}
Update: The OR operator is something you should learn in the first couple weeks. The only thing more basic is to just write out the second if statement.
if(Level.equals("9"))
{
//Senior
}
else if(Level.equals("10"))
{
//Senior
}
I'm hoping someone can help me here. I'm getting the error:
Main method not found in class Pythag, please define the main method as:
public static void main(String[] args)
But as you can see in the code below it is there? So why the error? This seems to happen a lot
to my classes in Eclipse Java EE IDE.
public class Pythag {
// All Java applications have a main() method.
// This one does a simple Pythagorean calculation.
public static void main(String[] args) {
// Declare fields and initialise values(input).
int firstNum = 17;
int secondNum = 6;
int answer;
// Do the calculation (process).
//
answer = (firstNum * firstNum) + (secondNum * secondNum);
// Display the results (output).
//
System.out.println("The square of the hypotenuse is "
+ "equal to the sum of the squares "
+ "of the other two sides.");
System.out.println("For example...");
System.out.println(answer + " = " + firstNum + " squared + "
+ secondNum + " squared.");
}
}
I just tried VALIDATING my code and it then ran fine? Not sure what the problem was or why it wouldn't work but validating the code seemed to sort it out so, there we go?
Assuming this class is defined in a file called Pythag.java it can be compiled and run like this:
$ javac Pythag.java
$ java Pythag
The square of the hypotenuse is equal to the sum of the squares of the other two sides.
For example...
325 = 17 squared + 6 squared.
This output was generated by copying your code sample directly into a file called Pythag.java with no edits.
Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}