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);
}
}
Related
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
This is my first semester doing computer programming and our professor totally bailed on us mid class. But I managed to nearly complete the classwork but for some reason my while statement is getting skipped.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
//this is where it skips from here*********
while (response == "y")
{
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
if (response =="y")
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
}
}
while (response == "n");
//to here*********************************************
System.out.println("Final Tally");
System.out.println("Polly received:\t " + totalPolly + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + totalErnest + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
Strings effectively point to values in Java, and aren't values themselves. Try using
while (response.equals("y"))
instead of
while (response == "y")
In the former case you're telling the runtime to actually compare the values. The latter case is telling the runtime to compare the pointers, which may not actually match.
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);
I'm new to java programming and currently making this raffle program. Here is the sample output of the program.
Welcome to raffle 2013!
The Prize is <10 million - 100 million> //this is random. I already made.
Ticket number: <Generating unique 10 digits numbers>
//these are the required information for the user.
Name:
Address:
Contact:
Birthday:
//The final output
The winner of <PRIZE> is <NAME>, Ticket number.
I already have written some source code and I think I'm almost there. Unfortunately, I encountered a problem with the ticket number. The ticket number must generate 5 times with 10 digits number. The output must show the winner name together with his/her ticket number but the ticket number wasn't show and state that it is null. Here are the syntax I already made.
public class raffle2013 {
//Title: Raffle 2013
public static final int SIZE = 5;
public static final int SIZE1 = 5;
private static short x;
private static String randomNumber;
public static void main(String[] args) {
String[] names;
names = new String[SIZE];
String[] winner;
winner = new String[SIZE1];
System.out.println("Welcome To Raffle 2013");
long Low = 10000000;
long High = 100000000;
long randomPrize = (long) (Math.random() * High - Low) + Low;
System.out.println("The Prize is " + " " + randomPrize);
for (int a = 0; a < winner.length; a++) {
long randomNumber = (long) (Math.random() * 9000000000L);
System.out.println("Ticket number: " + randomNumber);
Scanner scan = new Scanner(System.in);
System.out.print("Name " + ":");
winner[a] = scan.nextLine();
Scanner scan2 = new Scanner(System.in);
System.out.print("Address" + ":");
names[x] = scan.nextLine();
Scanner scan3 = new Scanner(System.in);
System.out.print("Contact" + ":");
names[x] = scan.nextLine();
Scanner scan4 = new Scanner(System.in);
System.out.print("Birthday" + ":");
names[x] = scan.nextLine();
System.out.println(" ");
}
Random random = new Random();
int w = random.nextInt(SIZE1);
System.out.println("The winner of" + " " + randomPrize + " " + "Million Peso(s)" + "is" + " " + winner[w] + "," + " " + "Ticket Number:" + " " + randomNumber);
}
}
Note: the program can generate 10 digits unique numbers for the ticket number and generate it 5 times together with the names, however I have a problem of choosing the ticket number winner.
Here is the output in java netbeans:
run:
Welcome To Raffle 2013
The Prize is 38375493
Ticket number: 1991318978
Name :a
Address:a
Contact:a
Birthday:a
Ticket number: 194313423
Name :b
Address:b
Contact:b
Birthday:b
Ticket number: 6017170047
Name :c
Address:c
Contact:c
Birthday:c
Ticket number: 274411236
Name :d
Address:d
Contact:d
Birthday:d
Ticket number: 6183250376
Name :e
Address:e
Contact:e
Birthday:e
The winner of 38375493 Million Peso(s)is a, Ticket Number: null<--- bug
BUILD SUCCESSFUL (total time: 18 seconds)
the last output must show the winner name together with his/her ticket number. I hope you could help me. Please :)
Actually you have created randomNumber of String type outside the loop , while inside you have created randomNumber of type long...this long type is only accessible within the loop and the randomNumber you are calling is the one which is string type and it is null because you havent assigned any value to it..
What you have to do is to have an array of the randomNumber and save the ticket numbers as well and in the last as you are getting the winner[w] the same way you get randomNumber[w]
Looks like you're running into an issue with scope. You may also be slightly confused about data types, but let's see...
randomNumber is assigned as a long inside of your loop, but it is declared as a static String inside your class. The declaration inside of the loop is not applicable when coming to a wider scope (that is, inside of your main method), so you won't get any pertinent values from randomNumber.
That's weird in and of itself - the different data types don't make sense to me. You also don't need the static declaration of randomNumber either - it's only ever used in main, so you could just declare it there.
To get around that, you have to wrap the output from your random input instead, and drop the declaration:
randomNumber = Long.toString(Double.valueOf(Math.random() * 9000000000L).longValue());
Also, as a code smell, you've got too many Scanner instances; you should only really need one. I leave that as an exercise to the reader to clean up and refactor.
Similar to storing the winner, the ticket number has to be stored as well, and recalled when the output is printed
import java.util.Random;
import java.util.Scanner;
public class raffle2013 {
// Title: Raffle 2013
public static final int SIZE = 5;
public static final int SIZE1 = 5;
private static short x;
private static String randomNumber;
public static void main(String[] args) {
String[] names;
names = new String[SIZE];
String[] winner;
winner = new String[SIZE1];
long[] ticketNumber = new long[SIZE1];
System.out.println("Welcome To Raffle 2013");
long Low = 10000000;
long High = 100000000;
long randomPrize = (long) (Math.random() * High - Low) + Low;
System.out.println("The Prize is " + " " + randomPrize);
for (int a = 0; a < winner.length; a++) {
long randomNumber = (long) (Math.random() * 9000000000L);
System.out.println("Ticket number: " + randomNumber);
Scanner scan = new Scanner(System.in);
System.out.print("Name " + ":");
winner[a] = scan.nextLine();
ticketNumber[a] = randomNumber;
Scanner scan2 = new Scanner(System.in);
System.out.print("Address" + ":");
names[x] = scan.nextLine();
Scanner scan3 = new Scanner(System.in);
System.out.print("Contact" + ":");
names[x] = scan.nextLine();
Scanner scan4 = new Scanner(System.in);
System.out.print("Birthday" + ":");
names[x] = scan.nextLine();
System.out.println(" ");
}
Random random = new Random();
int w = random.nextInt(SIZE1);
System.out.println("The winner of" + " " + randomPrize + " "
+ "Million Peso(s)" + "is" + " " + winner[w] + "," + " "
+ "Ticket Number:" + " " + Long.toString(ticketNumber[w]));
}
}
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.