No output from System.out.println in method - java

import java.util.Scanner;
public class RentalDemo
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
String cnumber;
String outnumber;
Rental first=new Rental();
System.out.print("Enter the contract number: ");
cnumber = input.next();
first.setContractNumber(cnumber);
outnumber=first.getContractNumber();
System.out.println("The contract number is: "+outnumber);
Rental Hours = new Rental();
double Hourss = Hours.getHours();
Rental Minutes = new Rental();
double Minutess = Minutes.getMinutes();
SammysRentalPriceWithMethods motto = new SammysRentalPriceWithMethods();
motto.companyMotto();
}
****public static void AlmostThere(double Minutess, double Hourss)
{ double Total_Cost = Hourss * 40 + Minutess;
System.out.println("You rented our equipment for " + Hourss + "complete hours and "+ Minutess + " extra minutes!");
System.out.println("The total cost of a " + Hourss + " hour rental, with " + Minutess + "extra minutes is " + Total_Cost + "at a $40 rate/hr with a $1 rate/extramin!");**
}
This last section here is the part that isn't printing out when I run it, any ideas why? I'm sorry if I wasn't thorough,** I was expecting it to take the correct numbers and show it to the reader but it just gets through the Main method and stops.

You're never calling the AlmostThere() method. That's what's going to print out everything for you.
At the end of your main() method do something like:
AlmostThere(Hourss, Minutess);

You need to call the AlmostThere method or it will never be run.
Try adding
AlmostThere(Minutess,Hourss);
at the end of your Main method.

Its because you are not calling the method AlmostThere. Any method after the main method has to be called in order for you to see the output.
For example, to call you method you could write.
AlmostThere(45.0, 7.0));

Related

The JVM did not read one of the code, what is the issues? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I copy and paste this code into my Intellij and the result came out with the system does not allow the user to answer(input) the question "What is the three-letter currency symbol of your destination?" and it directly skip to the next question. May i know what is the issues and what is the solutions? Thank you for your teaching first.
This code I get from the link for my practice and study for Java : How to fix the error <identifier> expected?
package com.Test3;
import java.util.Scanner;
public class Example1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
intro(input);
time(input);
}
public static void intro(Scanner input) {
System.out.println("Welcome");
System.out.println("What is your name");
String name = input.nextLine();
System.out.println("Nice to meet you, " + name + " where are you travelling to?");
String dest = input.nextLine();
System.out.println("Great! " + dest + " sounds like a great trip");
}
public static void time(Scanner input) {
int hours, minutes;
float perd, perdc, change;
System.out.println("How many days are you going to spend travelling?");
int days = input.nextInt();
hours = days * 24;
minutes = hours * 60;
System.out.println("How much money in USD are you going to spend?");
float money = input.nextFloat();
perd = money / days;
System.out.println("What is the three letter currency symbol of your destination?");
String curr = input.nextLine();
System.out.println("How many " + curr + " are there in 1USD?");
float ex = input.nextFloat();
change = money * ex;
perdc = perd * ex;
System.out.println("If you are travelling for " + days + " that is the same as " + hours + " or " + minutes + " minutes");
System.out.println("If you are going to spend " + money + " $USD that means per day you can spend upto $" + perd + " USD");
System.out.println("Your total budget in " + ex + " is " + change + ex + " ,which per day is " + perdc + curr);
}
}
Do not use nextLine. It does what the docs say it does, but it's not what you want, hence, 'broken'.
Instead, properly configure your scanner; after making it, invoke: scanner.useDelimiter("\\R"); (which tells the scanner that tokens are separated by newlines), and use .next() to read a line of text.

Variable Scope and Visibility in Java

I am making a vacation and vacationdriver. The vacation file will serve as my blueprint and the driver will be the interactive portion of the program creating instances of vacation. I have everything working perfectly, but when I add in the one value I am missing to my print statement of line 47 of the vacation driver class I break the program.
I need to call the value for numSales which I thought is declared in line 42. When I type in numSales on line 47 at the beginning and in the middle of the output as shown I get a red line underneath and Eclipse tells me "numSales cannot be resolved into a variable". What do I need to do to get the value of numSales to be actively output in the print statement on line 47 of the vacation driver?
Here is the vacation class:
package cbrownmod4;
import java.text.NumberFormat;
public class Vacation {
// money formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
// instance variables
private String vacationName;
private int numSold;
private Double priceEach;
// empty constructor
public Vacation() {
}
// partial constructor
public Vacation(String n, int s, double e) {
vacationName = n;
numSold = s;
priceEach = e = 0;
}
// updatSales method
public int updateSales() {
int updateSales = 0;
updateSales = updateSales + numSold;
return updateSales;
}
// totalValue method
public double totalValue() {
double totalValue = 0;
totalValue = totalValue + (numSold * priceEach);
return totalValue;
}
// toString method
public String toString() {
return vacationName + " has been sold " + numSold + " times for " + money.format(priceEach) +
" each for a total value of " + money.format(numSold*priceEach);
}
// getters and setters
public String getVacationName() {
return vacationName;
}
public void setVacationName(String vacationName) {
this.vacationName = vacationName;
}
public int getNumSold() {
return numSold;
}
public void setNumSold(int numSold) {
this.numSold = numSold;
}
public Double getPriceEach() {
return priceEach;
}
public void setPriceEach(Double priceEach) {
this.priceEach = priceEach;
}
}
Here is the vacation driver:
package cbrownmod4;
import java.text.NumberFormat;
import java.util.Scanner;
public class VacationDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// ask for the number of vacations and read it into numVacations
System.out.println("How many vacations are there?:");
int numVacations = input.nextInt();
// ask for the number of sales people and read it into numPeople
System.out.println("How many sales people are there?: ");
int numPeople = input.nextInt();
// beginning of loop for number of vacations
for(int i = 0; i < numVacations; i++) {
//ask for the name and price and read these into variables
System.out.println("What is the name of vacation #" + Integer.toString(i+1) + "?:");
String name = input.next();
System.out.println("How much does " + name + " cost?: ");
Double price = input.nextDouble();
// create a Vacation instance using the data obtained above
Vacation vacay = new Vacation (name, i, price);
// loop through the sales people
for(int j = 0; j < numPeople; j++) {
// ask for the sales for the current vacation and read it in
System.out.println("What are the sales for the current vacation by person #" + Integer.toString(j+1) + "?:");
int numSales = input.nextInt(); // line 42
// call updateSales with this number
numSales = vacay.updateSales();
} //end of inner loop
//where line 47 begins
//print out this vacation info
System.out.println(numSales + " trips to " + name + " were sold for " + money.format(price) + " for a total of " + money.format(numSales * price));
} //end of outer for loop
} //end of main
}
Due to requests to provide a snippet of the portion of the code not working here is the bit thats proving me problems:
//print out this vacation info
System.out.println(numSales + " trips to " + name + " were
sold for " + money.format(price) + " for a total of " +
money.format(numSales * price));
NOTE: If you take out the numSales in the snippet of the vacation driver, the program executes correctly but does not have the correct output because it is missing the necessary output variable
The clear concise question would be - why doesn't numSales work when I use it like shown in the short snippet. Again my problem is that Eclipse says "numSales cannot be resolved into a variable."
The problem is that you declare numSales inside a for {} block.
You need to declare it before the for block:
int numSales = 0; // set initial value in case numPeople is 0 and the loop never runs
// loop through the sales people
for(int j = 0; j < numPeople; j++) {
// ask for the sales for the current vacation and read it in
System.out.println("What are the sales for the current vacation by person #" + Integer.toString(j+1) + "?:");
numSales = input.nextInt(); // line 42; this value is never used? it is overwritten below
// overwrite the never-used value from line 42??
numSales = vacay.updateSales();
} //end of inner loop
// now numSales is still visible, because it was declared on this same 'level' and not in an inner block
System.out.println("numSales: " + numSales);
The value set in line 42 is never used, and is overwritten in line 45, so you might as well call input.nextInt(); without setting the value to numSales.

Beginner Java: Simple grade average code

I'm trying to understand the different parts of the code but I need to ask for individual help at this point. So here's my issue: I'm building a simple grade average program for my first java programming class. I want to save 4 grade inputs, then display an average. Eventually I am going to display letter grades based on that average. I think this error is saying I am not initializing finalGrade.
But I'm lost. An explanation of what is happening would be great so I can actually learn this.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GradeAverage{
public static Double gradeQ1; //gradeQ are grades for the respective quarters
public static Double gradeQ2;
public static Double gradeQ3;
public static Double gradeQ4;
public static String studentName;
public static Double finalGrade = ((gradeQ1 + gradeQ2 + gradeQ3 + gradeQ4) / 4);
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
studentName = JOptionPane.showInputDialog(null, "Please enter your first and last name.");
JOptionPane.showMessageDialog(null, "Thanks " + studentName + ", let's get started!");
gradeQ1 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the first quarter?")); // gets grade and saves it as a double gradeQ1
JOptionPane.showMessageDialog(null, "You entered " + gradeQ1);
//double gradeQ1 = input.nextDouble();
gradeQ2 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the second quarter?"));
JOptionPane.showMessageDialog(null, "You entered " + gradeQ2);
gradeQ3 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the third quarter?"));
JOptionPane.showMessageDialog(null, "You entered " + gradeQ3);
gradeQ4 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the fourth quarter?"));
JOptionPane.showMessageDialog(null, "You entered " + gradeQ4);
JOptionPane.showMessageDialog(null, "Thanks " + studentName + ", Your average was " + finalGrade);
}
}
JGRASP error:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at GradeAverage.<clinit>(GradeAverage.java:15)
Your program fail on:
public static Double finalGrade = ((gradeQ1 + gradeQ2 + gradeQ3 + gradeQ4) / 4);
because grade* are object and they haven't got initialization. The program could work only in case you use double instead Double. The different is that the first isn't an object and its default value is 0.0 , while Double is an object with default value null. This create the nullPointerException.
Second your finalGrade will be 0, you must before read the value and then set the finalGrade's value.
...
JOptionPane.showMessageDialog(null, "You entered " + gradeQ4);
finalGrade = ((gradeQ1 + gradeQ2 + gradeQ3 + gradeQ4) / 4);
JOptionPane.showMessageDialog(null, "Thanks " + studentName + ", Your average was " + finalGrade);

How to Declare and read values into integer variables?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
this is what ive tried
import java.util.Scanner;
class VariableExample
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
string e = scan.next();
string f = scan.next();
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
}
i told you... im really new
You forgot to declare entry point i.e. main() method, String S should be capital and in System.out.println() you used wrong variables:
class VariableExample {
public static void main(String... args) { // Entry point..
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
String e = scan.next(); // String S should be capital..
String f = scan.next();
System.out.println("Your integer is: " + a + " " + b + ", your real number is: " + c + " " + d
+ " and your string is: " + e + " " + f); // here you used wrong variables
}
}
If still your problem not clear then let me know where you actually stuck.
There are a couple of issues.
(1) You need to declare an "entry" point for your program. In Java, you must create a method with the exact signature:
public static void main(String args) {
// Your code here
}
(2) The "string" type in Java is capitalized.
(3) You are referencing variables that have been neither declared nor defined:
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
In this case, you've never told Java what the value of intValue, etc is. It seems like you want to use the variables you have declared and defined like:
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
(4) It looks like you're reading in two sets of variables for each prompt. Based on your prompt "Please enter an...", you really are expecting one input.
Altogether, I think your code should look like this:
class VariableExample {
public static void main(String args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value: ");
int a = scan.nextInt();
System.out.println("Please enter a double value: ");
double c = scan.nextDouble();
System.out.println("Please enter a string: ");
String e = scan.next();
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
}
}

Problem with weight conversion program

import java.util.Scanner;
import java.text.DecimalFormat;
public class WeightConverter
{
private double numOfLbs2Conv, numOfKilos2Conv, converted2Pounds, converted2Kilograms;
private final double WEIGHT_CONVERSION_FACTOR = 2.20462262;
private int desiredDecimalPlaces;
private boolean toKilos, toPounds;
public void readPoundsAndConvert()
{
toKilos = true;
System.out.print("Enter the number of pounds to convert to "
+ "kilograms: ");
Scanner keyboard = new Scanner(System.in);
numOfLbs2Conv = keyboard.nextDouble();
converted2Pounds = numOfLbs2Conv / WEIGHT_CONVERSION_FACTOR;
}
public void readKilogramsAndConvert()
{
toPounds = true;
System.out.print("Enter the number of kilograms to convert to "
+ "pounds: ");
Scanner keyboard = new Scanner(System.in);
numOfKilos2Conv = keyboard.nextDouble();
converted2Kilograms = numOfKilos2Conv * WEIGHT_CONVERSION_FACTOR;
}
public void displayBothValues()
{
System.out.print("How many places after the decimal would you like? ");
Scanner keyboard = new Scanner(System.in);
desiredDecimalPlaces = keyboard.nextInt();
String decimalCounter = "0.";
for (int i = 0; i < desiredDecimalPlaces; i++)
{
decimalCounter = decimalCounter + "0";
}
DecimalFormat decimalsConverted = new DecimalFormat(decimalCounter);
if (toKilos)
{
System.out.println("The number of kilograms in "
+ decimalsConverted.format(numOfLbs2Conv) + " pounds is "
+ decimalsConverted.format(converted2Kilograms) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
if (toPounds)
{
System.out.println("The number of pounds in "
+ decimalsConverted.format(numOfKilos2Conv) + " kilograms is "
+ decimalsConverted.format(converted2Pounds) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
}
}
Hi all.I'm having trouble getting this together. The output is screwed. If the user converts to pounds (readPoundsAndConvert()) first, the output will say that the converted answer is 0. If the user convert kilograms first, the kilograms will convert properly and then for somereason the readPoundsAndConvert() method will be called an d behave properly. I have no clue why this is happening and have been spending hours on it. Can someone tell me how to get this to behave properly? If you need me to post the rest of the program, I will.
You're using your variables backwards... In readPoundsAndConvert() you're storing the converted value in converted2Pounds, but when you try to display it, you're reading from converted2Kilograms.
It looks like you're setting toKilos and toPounds to true in your two "convert" methods, but you aren't simultaneously setting the other to false. Thus, if you've called one of the convert methods before, when you call displayBothValues() both toKilos and toPounds will be true and both will be printed.

Categories

Resources