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.
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).
I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
I am trying to write to an outfile.txt using variables that are inside if statements.
when I compile it it keeps saying the variable has not been initialized when in fact they have been, one as a string and char as the other.
import java.io.*;
import java.util.Scanner;
public class program5{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
public static void main(String[] args) throws IOException{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int i, gradeA_count = 0, gradeB_count = 0, gradeC_count = 0,
gradeD_count = 0, gradeF_count = 0, first_grade,
second_grade, third_grade, fourth_grade,
total_of_grades;
String remarks, course_name, semester, instructor_name, student_name;
char grade;
double average_grade;
int[] array_of_int_numbers = new int[10];
Scanner sc = new Scanner(System.in);
// set up a outfile to write to
Writer outfile = new BufferedWriter(new FileWriter("e:outfile.txt"));
// Write the class information to the outfile
outfile.write(" CMPS 161 Program Five, Fall 2015\n\n");
// separate top and next line for ease of sight
outfile.write(" -------------------------------- \n\n");
System.out.println("Enter the course name: ");
course_name=input.readLine();
System.out.println("Enter the Semester: ");
semester=input.readLine();
System.out.println("Enter the Instructor: ");
instructor_name=input.readLine();
outfile.write("Course: " +(String.format("%-8s",course_name))+ " Semester: " +(String.format("%-10s",semester))+ " Instructor: " +(String.format("%-12s",instructor_name))+ "\n\n");
outfile.write("Array Item Student Name T1 T2 T3 T4 Avg Grade Remarks\n\n");
outfile.write("=================================================================\n\n");
// array initialization
for (i = 0; i < 1; i++) array_of_int_numbers[i] = 0;
// prompt user for a value into the array
for (i = 0; i < 1; i++){
System.out.println("Enter a Students Name: ");
student_name=input.readLine();
System.out.println("Enter the first grade: ");
first_grade=sc.nextInt();
System.out.println("Enter the second grade: ");
second_grade=sc.nextInt();
System.out.println("Enter the third grade: ");
third_grade=sc.nextInt();
System.out.println("Enter the fourth grade: ");
fourth_grade=sc.nextInt();
total_of_grades = first_grade + second_grade + third_grade + fourth_grade;
average_grade = (double) total_of_grades / 4.0;
System.out.println("Your average grade is " +(String.format("%.1f",average_grade))+ "\n");
if (average_grade >= 90){
remarks = "Excellent";
grade = 'A';
gradeA_count++;
}else if (average_grade >= 80){
remarks = "Very Good";
grade = 'B';
gradeB_count++;
}else if (average_grade >= 70){
remarks = "Good";
grade = 'C';
gradeC_count++;
}else if (average_grade >= 60){
remarks = "Poor";
grade = 'D';
gradeD_count++;
}else if (average_grade >= 0){
remarks = "Fail";
grade = 'F';
gradeF_count++;
}
outfile.write("["+i+"]"+ student_name +
"" + first_grade +
"" + second_grade +
"" + third_grade +
""+ fourth_grade +
"%" + average_grade +
"" + grade +
"" + remarks + "\n");
}
for (i = 0; i < array_of_int_numbers.length; i++){
System.out.println("array_of_int_numbers["+(i+1)+ "] = "+array_of_int_numbers[i]);
}
System.out.println("Number of A's : " + gradeA_count);
System.out.println("Number of B's : " + gradeB_count);
System.out.println("Number of C's : " + gradeC_count);
System.out.println("Number of D's : " + gradeD_count);
System.out.println("Number of F's : " + gradeF_count);
outfile.close();
} // end program
} // end class
I am new to coding (only my fifth program) and this is my first semester in college, any help would be greatly appreciated.
I am using JGrasp as my professor requires it and coding in java.
Edit:
Here are the exceptions being thrown:
program5.java:107: error: variable grade might not have been initialized
"" + grade +
^
program5.java:108: error: variable remarks might not have been initialized
"" + remarks + "\n");
^
At the beginning of the program, when you declare grade and remarks, you aren't initializing it. You must set these variables to a default value.
For example:
String remarks = "";
char grade = '0';
It doesn't really matter what they're set to right now, because they'll be changed later.
Now, if you know that average_grade will never be negative, then you can replace that last else if statement with a simple else. This is why Java thinks that the variables may not be initialized, because there is the possibility that average_grade could become negative.
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);
}
}
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.