This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
My code works fine except for the part where I am supposed to ask the user if they would like to quit the program. It's a simple y/n that should trigger the entire program to repeat if 'n' is entered and terminates when 'y' is entered. I know i need to use a while loop but i just can't figure out exactly how I need to write it in code so that it works like expected.
import java.util.*;
public class MilitaryTime
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
String answer = in.next();
while (answer != "n")
{
}
}
}
You should probably split your code in (at least) two different methods, but I'll just try to point out a way to achieve what you want with minimal changes:
public static void main (String [] args)
{
String answer = null; // you have no answer yet...
do { // ... but you want to execute your stuff at least once
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
answer = in.next();
} while (!answer.equalsIgnoreCase("n"));
}
Until then rerun the main method.
while (answer.equals("n")) // comment by drewmoore; its helpfull for strings..
{
// you said, program should repeat if n is pressed.
// so, if answer is equal to n then execute the main function.
main();
}
This would execute until the user presses some other button.
Secondly, you don't need to use while loop. This can be done using if too.
Related
I am supposed to make this code output Day total and then the number of hours worked for that day. The code is currently displaying the day and the total. But it is displaying too many times for the program to even register. For instance, it asks to input a day, and I'll put in Monday. Then the number of hours worked, and I'll put 6. It will then output Monday 6.0 thousands of times. The expected output should be Day Total 6. What am I missing or is added to cause this?
// SuperMarket.java - This program creates a report that lists weekly hours worked
// by employees of a supermarket. The report lists total hours for
// each day of one week.
// Input: Interactive
// Output: Report.
import java.util.Scanner;
public class SuperMarket
{
public static void main(String args[])
{
// Declare variables.
final String HEAD1 = "WEEKLY HOURS WORKED";
final String DAY_FOOTER = " Day Total "; // Leading spaces are intentional.
final String SENTINEL = "done"; // Named constant for sentinel value.
double hoursWorked = 0; // Current record hours.
String hoursWorkedString = ""; // String version of hours
String dayOfWeek; // Current record day of week.
double hoursTotal = 0; // Hours total for a day.
String prevDay = ""; // Previous day of week.
boolean done = false; // loop control
Scanner input = new Scanner(System.in);
// Print two blank lines.
System.out.println();
System.out.println();
// Print heading.
System.out.println(HEAD1);
// Print two blank lines.
System.out.println();
System.out.println();
// Read first record
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if(dayOfWeek.compareTo(SENTINEL) == 0)
done = true;
else
{
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
hoursWorked = Integer.parseInt(hoursWorkedString);
prevDay = dayOfWeek;
}
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
System.out.println(dayOfWeek + " " + hoursWorked + hoursTotal);
hoursTotal++;
if(dayOfWeek.compareTo(SENTINEL) == 0)
{
hoursWorked = dayOfWeek.compareTo(SENTINEL);
prevDay = dayOfWeek;
done = true;
}
else
done = false;
// Include work done in the dayChange() method
if(dayOfWeek.compareTo(SENTINEL) == 0)
System.out.println(DAY_FOOTER + hoursTotal);
System.exit(0);
} // End of main() method.
} // End of SuperMarket class.
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
In this code block, you aren't changing done variable, so it is an infinite loop.
My program consists of several options of what to do with user input data about shows (name, day, time). One of the options is to display the data and the total number of shows per day (ex: if there are 2 shows on Tuesday, it will display "There are 2 shows on Tuesday"). So far the output for displaying all the data is working but when it comes to displaying the number of shows on a specific day, it isn't working properly. I've read several other java programs that seem to have a switch statement on each day but that hasn't worked either. If there are any suggestions on what I should change about my code, I would truly appreciate it! Thank you
I have edited my code from the previous one but it still hasn't worked
Note: the int dayCount is placed in the enter data method; after the day[i] = br.readLine();
Here is my class:
import java.io.*;
public class Javavision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String name[] = new String[1000];
static String day[] = new String[1000];
static String time[] = new String[1000];
static int dayCount = 0;
static int x, i, j, smallest;
static String temp;
Here is my code:
public static void showShows() {
//output all shows
for (i = 0; i < x; i++) {
System.out.println("Name : " + name[i]);
System.out.println("Day : " + day[i]);
System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
} **The problem is here**
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
}
Here is the output:
Name : The Flash
Day : Sunday
Time(2:30 am = 0230) : 0125
Name : Suits
Day : Sunday
Time(2:30 am = 0230) : 0450
Name : Java Program
Day : Tuesday
Time(2:30 am = 0230) : 0330
There is 3 shows on Sunday
This is where I increment dayCount:
//Method addShow
public static void addShow() throws IOException {
//initialize counter
x = 0;
do {
//Update Array
System.out.println("Enter Name of Show: ");
name[x] = in.readLine();
System.out.println("Enter Day of Show: ");
day[x] = in.readLine();
dayCount++;
System.out.println("Enter Time of Show (ex: 2:30am = 0230) : ");
time[x] = in.readLine();
//Increase counter
x++;
//Ask if the user wants to stop
System.out.println("\nTo continue press Enter ");
System.out.println("To Quit, type in 'quit': ");
}
while((in.readLine().compareTo("quit"))!=0);
//Method addShow()
}
In your loop that prints the total shows you have:
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
The if(i == 0) makes it so that the println only executes on the first iteration of the loop. Take out the if statement and have:
for (i = 0; i < x; i++) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
And this should print out the rest of the days
Also you only have one dayCount variable that you use for all the days. So no matter what day a show is on, you increment dayCount. (If you have three shows on different days you still increment dayCount everytime so it shows that you have three shows on each day when you print it out) If you want to have a separate dayCount variable for every day, I recommend using a Hashmap.
(Using the day as the key and the dayCount as the value)
Also you could look into enums to use for the days of the week.
This question already has answers here:
How can I prevent java.lang.NumberFormatException: For input string: "N/A"?
(6 answers)
Closed 5 years ago.
Hi I'm a beginner in Java and I am trying to write this program where I can enter numbers, but that when I enter "done", I get the values that I called total, numberInputs. However when i run it and that i input "done" I get Exception in thread "main" java.lang.NumberFormatException: For input string: "done". Do you know how I can fix this please?
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at repeat.numberReader(repeat.java:15)
at repeat.main(repeat.java:23)
This is my code:
import java.util.Scanner;
public class repeat{
public void numberReader(){
Scanner myScanner = new Scanner(System.in);
int total = 1;
int numberInputs = 1;
String userInput;
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
total = total + Integer.parseInt(userInput);
numberInputs++;
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
public static void main(String[] args){
repeat instance = new repeat();
instance.numberReader();
}
}
Thank you for your help
As indicated by the website: NumberFormatException, the exception is caused by trying to convert a string that does not represent a number, to an integer, in this case: "done"
The exception is triggered in this line:
total = total + Integer.parseInt(userInput);
You can avoid and handle this exception as follows:
public class repeat{
public void numberReader(){
Scanner myScanner = new Scanner(System.in);
int total = 1;
int numberInputs = 1;
String userInput;
boolean done = false; // Stop when true
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
try{ // Managing the exception
total = total + Integer.parseInt(userInput);
} catch(NumberFormatException e){
if ("done".equals(userInput)){ // it's done!!!!
done = true;
}
}
numberInputs++;
} while (!done);
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
public static void main(String[] args){
repeat instance = new repeat();
instance.numberReader();
}
}
Read more about the try / catch
The problem with your code is in this line
total = total + Integer.parseInt(userInput);
Suppose user enters the String "done".
now your code will try to parse the string to integer i.e.
total=total+Integer.parseInt("done");
Therefore , NumberFormatException will occur.
The correct code will be
import java.util.Scanner;
public class repeat{
public void numberReader(){
Scanner myScanner = new Scanner(System.in);
int total = 1;
int numberInputs = 1;
String userInput;
while (true)
{
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
if("done".equals(userInput))
{
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
break;
}
else
{
total = total + Integer.parseInt(userInput);
numberInputs++;
}
}
}
public static void main(String[] args){
repeat instance = new repeat();
instance.numberReader();
}
}
You are checking userInput for the value "done", but you do it AFTER the call to Integer.parseInt(). Calling Integer.parseInt("done") is throwing the NumberFormatException as the string "done" cannot be parsed as an integer.
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
***ERROR HERE***
total = total + Integer.parseInt(userInput);
numberInputs++;
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
You can resolve this a couple of ways. The simplest would be to reorder your code so that you check the input immediately after receiving it and only parse it after. This does require having the prompt twice though (once before the loop, and once at the bottom of it. This will also have issues if the first entry is "done" as a do-while loop always executes at least one time. You could change to a standard while loop to avoid this. This also will not handle strings other than your expected "done" string.
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
do {
total = total + Integer.parseInt(userInput);
numberInputs++;
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
Alternatively, you can also implement error handling to catch and handle the exception, but that is a bit more complicated. This sounds like homework, and error handling is probably beyond your scope, so i'd just consider the first option.
As a side note, you should consider changing "done".equals(userInput) to userInput.equals("done"). They are functionally identical, however the second statement is much more clear what your intent is, which is to see if userInput is "done". The first is harder for yourself and others to read and understand.
you need to check if input is "done" before using Integer.parseInt(userInput)
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
if(!"done".equals(userInput)){
total = total + Integer.parseInt(userInput);
numberInputs++;
}
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
I'm having a little problem here.
We been told to program some simple things but I can't run the code perfectly with if statement.
With while statements, my code works perfectly but teacher insists not to use it.
While statement is a loop right?
He said "Do not use loops!".
import java.util.Scanner;
public class Flight
{
public static void main (String [] args)
{
// Naming a scanner //
Scanner scan = new Scanner(System.in);
// Prints text //
System.out.println("Enter flight day: ");
// Data insert //
int flyDay = scan.nextInt();
System.out.println("Enter flight hour: ");
int flyHour = scan.nextInt();
System.out.println("Enter flight minute: ");
int flyMinute = scan.nextInt();
//// Length ///
System.out.println("Enter flight's length in hours:");
int departureHour = scan.nextInt();
System.out.println("Enter flight's length in minutes:");
int departureMin = scan.nextInt();
// While minute is beyond 60 (including) //
departureMin += flyMinute;
while(departureMin >= 60) {
departureHour++;
departureMin-=60;
}
// While hour is beyond 24 (including) //
departureHour += flyHour;
while(departureHour >= 24)
{
flyDay++;
departureHour-=24;
}
// While day is beyond 8 (including) //
while(flyDay >=8)
flyDay-=7;
// Prints arrival time according to the data inserted above //
System.out.println("the supposed arrival time is: day- " + flyDay + ", hour- " + departureHour + ", minute- " + departureMin);
}
}
If I switch the while statements into if statements the code will not work properly.
Any help?
Your teacher is correct, it's not appropriate to use a loop here, even though it works.
Your teacher probably wants you to use the remainder (%) (frequently called "modulus") operator and the division (/) operator.
Hey guys , thanx for the previous help Before I try to explain my problem, you guys need to know what the code is about. Its pretty much "To write a game in which a user is to guess a random number between 1 and 1000. The program should read a number from the keyboard, and print whether the guess was too high, too low or correct. When the user has guessed correctly, the program prints out the numbe of guesses made and time and the playername.When a game is started the program must print the entire high score list, sorted by the number of guesses in ascending"
The Issue is when playing the game and when you manage to get the correct answer it doesn't show the time but when the highscore is printed it shows there, Whats up with that because tried to change the boolean statement but that didn't see to work. Here is an illustration of the problem:
You guessed 2 times in 0 seconds.
Please enter your name.
gert
Want to go again?(y/n).....n
HighScore:
Tries Time Name
1 35 b
2 6 gert
SO basically I'm pretty stuck, I was hoping that u guys could give me some pointers or some kind of help so I could fix the problem,,,,, Any help is appreciated.... BTW this is my first program, basically still in the learning phase So take it easy with the comments. The code is provided below:
import java.util.*;
import java.util.Scanner.*;
import java.util.ArrayList.*;
import java.util.Collections.*;
public class Main {
private static void start() {
int tries = 0 ;
int guess = -1;
String name ;
String quit = "quit";
String y = "yes";
String n = "no";
String currentGuess;
String another = ("y") ;
Scanner input = new Scanner (System.in);
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Long> tg = new ArrayList<Long>();
ArrayList<String> playern = new ArrayList<String>();
boolean a=false;
do {
a=false;
int answer = (int) (Math.random() * 1000 + 1) ;
System.out.println( " Welcome to Guessing Game " ) ;
System.out.print("Please enter a number between 1 and 1000 : ");
currentGuess = input.nextLine();
long startTime = System.currentTimeMillis();
do
{
if (currentGuess.equalsIgnoreCase(quit))
{
System.out.println("Leaving Us So Soon?");
System.exit(0);
}
try {
guess = Integer.parseInt(currentGuess);
} catch (NumberFormatException nfe)
{
System.out.println(" Dude Can You Read, Only Digits ");
currentGuess = input.nextLine();
continue;
}
if (guess < 1 || guess > 1000)
{
System.out.println("Stupid Guess I Wont Count That.");
currentGuess = input.nextLine();
continue;
}
if (guess < answer )
{
System.out.println("too low "+answer);
currentGuess = input.nextLine();
tries++;
}
else if(guess > answer )
{
System.out.println("too high "+answer);
currentGuess = input.nextLine();
tries++;
}
else if (guess == answer)
{
//stop stop watch
long endTime = System.currentTimeMillis();
//calculate game time
long gameTime = endTime - startTime;
gameTime = (gameTime/1000);
System.out.println("You Rock Dude, Good Job!");
System.out.println("You guessed " + tries + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.println("Please enter your name.");
name = input.nextLine();
score.add(tries) ;
playern.add(name);
tg.add(gameTime);
for ( int g=0; g < score.size()-1; g++){
for ( int b=g+1; b < score.size(); b++){
if (score.size()>1){
if (score.get (g) > score.get (b)){
Collections.swap(score, g, b);
Collections.swap(playern, g, b);
Collections.swap(tg, g, b);
}
}
if (score.get (g)==score.get(b) && tg.get (g) > tg.get(b))
{
Collections.swap(score, g, b);
Collections.swap(playern, g, b);
Collections.swap(tg, g, b);
}
}
}
boolean s = false ;
while (s==false)
{
System.out.print("Want to go again?(y/n).....");
currentGuess = input.nextLine();
if (currentGuess.matches("y"))
{
System.out.println("HighScore:");
System.out.println("Tries\tTimentName");
for (int j=0; j<score.size(); j++){
System.out.println(score.get(j) +"\t"+tg.get(j)+ "\t"+playern.get(j));
}
}
s=true;
}
//if user doesn't want to play again
if (currentGuess.matches("n"))
{ System.out.println("HighScore:");
System.out.println("Tries\tTime\t\tName");
for (int j=0; j<score.size(); j++){
System.out.println(score.get(j) +"\t"+tg.get(j)+ "\t"+playern.get(j));
}
System.out.println("Thanx For Playing.");
a=true;
s=true;
System.exit(0);
}
}
} while (guess != answer);
}while(a==false);
}
public static void main(String[] args) {
Main.start();
}
}
first you divide the time here
long gameTime = endTime - startTime;
gameTime = (gameTime/1000);
and then again here
System.out.println("You guessed " + tries + " times in " + (int)(gameTime/1000) + " seconds.");
no wonder why you get 0 :). so, don't divide again, just put gameTime
and then when you add to the tg Array List you add tg.add(gameTime); which is the correct time, that's why when you list the Highscores it works.
A couple of things here.
First, there is no Timer being used here. You are timing something in terms of actual time, but in Java, a Timer (such as java.util.Timer) is an object that schedules a repeated task.
Second, you should try to break up your code into smaller methods. These long, nested do/while loops are very hard to read because you can't see the whole loop without scrolling. Try keeping your methods shorter, and use multiple methods.
But, to answer your question about the time, you are dividing the time by 1000 twice when you try to display it. Your display line is
System.out.println("You guessed " + tries + " times in " + (int)(gameTime/1000) + " seconds.");
But you have already divided gameTime above
long gameTime = endTime - startTime;
gameTime = (gameTime/1000);
So in the display, you're not actually modifying gameTime again (which is why it stores as the proper value), but you are displaying gameTime/1000 (even though it has already been divided by 1000 once).
It is also a good thing for a starting developer to follow the simple indentation rules you've (hopefully) learned.
Also you should't write something like while(a==false); if a is a boolean just write while(a).
In this case you also do not have to use a do - while loop. A while loop will be more suited.