I'm trying to write a program that needs to stop when the target of £500 has been met. I have to use a DO WHILE loop to do this.
It needs to record how many donations it receives before it reaches £500, also it needs to record the name of the person with the highest donation given and what the largest donation was.
I cannot get the program to update the name of the person with the highest donation. The code I have so far is below. Please tell me where I am going wrong.
I have a red line coming up under 'namemax' when I try to call it at the end outside of the loop, saying 'not initialized'
enter codeimport java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 11/02/2015
* Time: 15:45
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class DoWhile
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
final double TOTAL=500;
String name,namemax;
double donation, donationTotal=0,currentMax=0;
int howManyDonation=0;
do
{
System.out.println("Please enter your name below");
name = keyboard.next();
System.out.println("");
System.out.println("Please enter the amount you would like to donate below");
donation = keyboard.nextDouble();
howManyDonation++;
donationTotal = donationTotal+donation;
if(donation>currentMax)
{
currentMax=donation;
namemax=name;
}//if
}//doWhile
while(donationTotal!=TOTAL);
System.out.println("The total number of donations is " + howManyDonation);
System.out.println("The largest donation was " + currentMax);
System.out.println("The name of the person with the largest donation is " + namemax);
}//main
}//class
here
Just change this line
String name,namemax;
into this:
String name,namemax = null;
Furthermore, change this
while(donationTotal != TOTAL);
into this:
while(donationTotal < TOTAL);
You have a pretty simple problem here. You are updating namemax inside of an if loop only. That means that as far as the code is concerned, there is a possible situation in which it could never be assigned. In practice, because of what you are doing, that can't actually happen but the compiler doesn't understand that.
To fix it,
change
string name,namemax;
to
string name;
string namemax = "";
That should take care of it.
it gives at least one sutuation where namemax not will be set. So you have to initialize the string.
Simply change
String name,namemax ;
To
String name,namemax = null;
or
String name,namemax = "";
The compiler can't guarantee that you'll actually set the namemax before you exit the loop. You should initialize namemax to the empty string to fix this problem.
Related
all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.
I am a very new Java user who just installed Eclipse two days ago. I am getting my feet wet by writing a program that ask's the user what grade they got on a test in percentage form and returning back what their grade is in letter form. I was also wondering how I can set this integer in an if-else statement so taht if the test grade is greater than or equal to 90, the program will return A for a grade. So on and so forth until 50 or below which would return an F. So far, all I have is this:
import java.util.Scanner;
public class gradechecker {
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
String test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
test_grade = user_input.next();
if(test_grade <= 90) {
}
}
}
To grab a integer value from the user, you use .nextInt().
In this case,
test_grade = user_input.nextInt();
test_grade gets the value entered from the user. However, test_grade is declared as a String variable. You'll need to change that to a int.
What August and azurefrog said are correct in terms of one part of your question, you want to use user_input.nextInt() instead of user_input.next() to get an int input from the user.
For the second part of your question, consider the best order to check the input and how to check the input.
I would consider using >= instead. Check for an A first, then B, etc. If something is >= 80 but you've already determined that it's not >= 90, you know it'll be a B. And remember to check if the user entered an invalid number as well. Remember to use if...else if...else to logically join the comparisons, otherwise you could end up with the wrong result.
Edit: As was pointed out, test_grade needs to be an int instead of a String.
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
You must use int to get the percentage in integer form
int test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
to get an input use input.nextInt... check the http://www.java-made-easy.com/java-scanner.html
test_grade = user_input.nextInt();
//Check for the conditions similar to this
if(test_grade >= 90) {
// assign the grade here
String grade = A;
// print the grade
System.out.println("your grade is"+grade)
}
After reading the string methods description in a chapter i was trying to solve this programming exercise. here it is.
Write a program that asks for the user's name and then writes that name to the monitor with either "Ms." or "Mr." in front, depending if the name is for a female or male. Assume that the only female names are
Amy
Buffy
Cathy
and that the only male names are
Elroy
Fred
Graham
All other names will be echoed without a title. The program continues looping until the user hits "enter" without first typing a name.
C:\>java Title
Enter a name:
Amy Johnson
Ms. Amy Johnson
Enter a name:
Fred Smith
Mr. Fred Smith
Enter a name:
Zoltan Jones
Zoltan Jones
Enter a name:
C:\>
here is my code i know its wrong because i am very confused.
import java.util.Scanner;
class titleApplier {
public static void main(String[] args) {
String name;
String male = {"Elroy" , "Fred " , " Graham"};
String females = {"Amy", "Buffy", "Cathy"};
Scanner scan = new Scanner(System.in);
while(name.hasNext()) {
System.out.println("Enter a name ");
name = scan.nextLine();
if(name.equals(male)) {
System.out.println("Mr " + male);
}
else if (name.equals(females)) {
System.out.println(" Mrs " + females);
}
else {
System.out.println(scan.nextLine());
}
}
}
}
You're mostly on the right track, good work!
Instead of storing the names in Strings individually, you could just reference them directly in your if statements as such:
if(name.equals("Elroy") || name.equals("Fred") || name.equals("Graham")) {
System.out.println("Mr " + male);
}
Also, since you're providing first and last names, I don't think you should be matching with the equals method, but instead, checking to see if the name contains one of the names:
if (name.contains("firstName"))
As this looks like homework, try something along the same lines for the women yourself. Let me know if you have anymore questions. Good luck!
There are plenty of errors in your program which need to be corrected.Better give this a try.I have used BufferedReader since the Scanner class causes some problems while taking several input values within a loop.:-
import java.io.*;
import java.util.*;
class MF{
static boolean search(String arr[],String st){
for(int i=0;i<arr.length;i++){
if(arr[i].equalsIgnoreCase(st)==true)
return true;
}
return false;
}
public static void main(String args[])throws IOException{
String male[]={"Elroy","Fred","Graham"};
String fem[]={"Amy","Buffy","Cathy"};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:-");
String st=br.readLine();
if(st.equals("")==false){
StringTokenizer str=new StringTokenizer(st);
String tok=str.nextToken();
if(search(male,tok)==true)
System.out.println("Mr."+st);
if(search(fem,tok)==true)
System.out.println("Ms."+st);
}
else
break;
}
System.out.println("Program terminates.");
}
}
A few observations from your code:
male and females should be arrays of String, not just a single String. (i.e. String[] females = {"Amy", "Buffy", "Cathy"};
Watch out for leading and trailing white spaces. "Fred" and "Graham" will never pass a comparison unless you call the String.trim() method.
The method hasNext() is not defined in the String class; thus the compilation error. If you are writing this on an IDE such as Eclipse, read the errors you are getting and resolve them. Even for a beginner this should not be difficult at all.
Your program prompts the user AFTER the name is already entered. This might be easier if you enclose your code in a do/while rather than in a while loop. This is a matter of preference, or course. Also, normally you would want the user input to appear in the same line as the prompt, so use System.out.print() for the prompt instead of System.out.println().
When you are learning, you should always try your programs with very controlled inputs. In this case, you should have tried the program with a single male name and female name, and once you got that part working, then you should try expanding your solution to handle multiple names.
Your code allows to enter a LINE (words separated by space) rather than a String (array of characters with no white spaces). Therefore, you need to break that line into tokens (words) and examine either the first token (first name) or the second token (last name) and compare it to the names in the array. Otherwise, the equals() method will return false. This is because 'Elroy Smith' is not equal to 'Elroy'. You can do what I just explained, or use other String methods such as contains() or startsWith().
You should append the title to the entered name, and not the first name in your String array. Instead of outputting "Mrs. Amy", your program should output "Mrs. Amy Smith".
Your while() clause does not capture this requirement: "The program continutes looping until the user hits "enter" without first typing a name." This method will always return true even if the line has a length of zero. Instead, use the String entered and loop only if the length of the String entered is larger than zero.
To eliminate unnecessary processing, you can use a boolean variable to see if the name has been found, in order to break (exit loop) or continue (skip to next iteration).
This is one potential solution (might not be the most effective, but easy for you to follow):
public static void main(String[] args)
{
String name;
String[] males = {"Elroy", "Fred ", " Graham"};
String[] females = {"Amy", "Buffy", "Cathy"};
Scanner scan = null;
do
{
System.out.print("Enter a name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
boolean found = false;
// Search all possible male names
for (String temp: males)
{
if (name.startsWith(temp))
{
System.out.println("Mr. " + name + "\n");
found = true;
break; // stop looping if found
}
}
if (found) { continue; } // skip the rest of the loop if name has been found
// Search all possible female names (only if name has not been found)
for (String temp: females)
{
if (name.startsWith(temp))
{
System.out.println("Ms. " + name + "\n");
found = true;
break;
}
}
if (name.length() > 0 && !found)
{
// A name was entered but it was never found
System.out.println("Unknown name entered.\n");
}
} while (name.length() > 0);
scan.close();
}
The output:
Enter a name: Fred Smith
Mr. Fred Smith
Enter a name: Buffy Vampire Slayer
Ms. Buffy Vampire Slayer
Enter a name: Cathy Doe
Ms. Cathy Doe
Enter a name:
Exiting program.
I am getting this message:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at fdc.programming.VendingMachine.InsertMoney(VendingMachine.java:70)
at fdc.programming.VendingMachineDriver.main(VendingMachineDriver.java:30)
Java Result: 1
I had been trying to work out, how to do a validate loop so that only positive integers can be accepted and I gave up for now, but I did not change anything and put everything back as it was before messing around. Now when I try to enter a number it gives the above error but there are no errors in Netbeans that I can use to figure out what is wrong! Please be aware that I have only done one basic module in Java for college ;)
My code is:
public class VendingMachine
{
String sinsertMoney, sinsertMoney2; // Money inserted value for parsing into int
String productName; // Name of product
int insertMoney, insertMoney2; // Money inserted by customer (int = pence)
int price; // Price of products on sale
int changeLeft; // Change left from inserted money after selection
int again; // variable for deciding program repeat
DecimalFormat pence = new DecimalFormat("#p"); // Format display output for pence
public void InsertMoney() {
String soption; // Variable for machine operation
productName = " Nothing";
insertMoney = 0; // Default inserted money initialised to zero
insertMoney2 = 0; // Default additional inserted money initialised to zero
price = 0; // Initialising money variables
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
if ("q".equals(soption)) { // If user chooses q: quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
}
if ("i".equals(soption)) { // if user chooses i: insert money
JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney); // Parsing for calculations
}
if ("s".equals(soption)) { // if user chooses s: select item
}
}
I can't see where you've declared sinsertMoney but it looks like you've forgotten to assign the result of your call to JOptionPane.showInputDialog to something, hence why that value is still null when you try to parse it.
Try this:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney);
You need to get the entered value in sinsertMoney like:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n=============================");
And also implement null check on the sinsertMoney for cancel operation and empty strings.
This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.
import java.util.Scanner;
public class Saturn
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");
String input;
int counter = 0;
while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();
counter++;
}
System.out.println("Your schedule consits of " + counter + " courses");
}
}
You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:
while (userInput.hasNextLine() &&
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}