This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I have fixed the errors in my original code and formatted it correctly. However, the code is now repeating String next() before it proceeds to the last method. I thought I understood why, but when I tried to fix it, the program failed again. Thank you for your time!
import java.util.Scanner;
public class LearnScanner {
public static void main (String[] args) {
first();
next();
third();
}
public static void first() {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Vacation Planner!!");
System.out.print("What is your name?");
String name = input.nextLine();
System.out.print("Nice to meet you " + name + ", where are you travelling to?");
String destination = input.nextLine();
System.out.println("Great! "+destination +" sounds like a great trip");
}
public static String next() {
Scanner input = new Scanner(System.in);
System.out.print("How many days are you going to spend travelling?");
String days = input.nextLine();
System.out.print("How much money in USD are you planning to spend on your trip?");
String budget = input.nextLine();
System.out.print("What is the three letter currency symbol for your travel destination?");
String currency = input.nextLine();
System.out.print("How many " + currency + " are there in 1 USD?");
String currencyConversion = input.nextLine();
return days;
}
public static void third() {
int days = Integer.valueOf(next());
int hours = days * 24;
int minutes = hours * 60;
System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
}
}
From what I see, the method next() gets called once from the main method, and then gets called again in third at
int days = Integer.valueOf(next());
Maybe you should create an instance variable called days and store the value of next() in it. Then use the value of the variable in the third() method. i.e.
import java.util.Scanner;
public class LearnScanner {
private static int days = 0;
public static void main (String[] args) {
first();
days = Integer.parseInt(next());
third();
}
public static void first() {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Vacation Planner!!");
System.out.print("What is your name?");
String name = input.nextLine();
System.out.print("Nice to meet you " + name + ", where are you travelling to?");
String destination = input.nextLine();
System.out.println("Great! "+destination +" sounds like a great trip");
}
public static String next() {
Scanner input = new Scanner(System.in);
System.out.print("How many days are you going to spend travelling?");
String days = input.nextLine();
System.out.print("How much money in USD are you planning to spend on your trip?");
String budget = input.nextLine();
System.out.print("What is the three letter currency symbol for your travel destination?");
String currency = input.nextLine();
System.out.print("How many " + currency + " are there in 1 USD?");
String currencyConversion = input.nextLine();
return days;
}
public static void third() {
int tempDays = Integer.valueOf(days);
int hours = days * 24;
int minutes = hours * 60;
System.out.println("If your are travelling for " + tempDays + " days that is the same as " + hours + " hours or " + minutes + " minutes");
}
Related
package stringvars;
import java.util.Scanner;
public class ConcertID {
public static void main(String[] args) {
try (Scanner userInput = new Scanner (System.in)) {
String yourName;
System.out.print ("enter the last letter of your second name: ");
yourName = userInput.next();
String yourDOB;
System.out.print ("enter your Year Of Birth: ");
yourDOB = userInput.next();
String ConcertID;
ConcertID = yourName + " " + yourDOB;
System.out.println("your concert ID is " + ConcertID);
}
}
}
I'm trying to get the code to take the user input, add a number between 1 and 10 at the end and print it as Y18867. Currently it prints as Y 1886.
(And I've yet to figure out the math.random part.)
Let me recommend you start using the StringBuilder class to create concatenated strings. It has a better performance regarding time consuming to concatenate strings.
The following code generates the random number as well as the concertId string that you are trying to get.
public class ConcertID
{
public static void main(String[] args)
{
try (Scanner userInput = new Scanner(System.in))
{
String yourName;
System.out.print("Enter the last letter of your second name: ");
yourName = userInput.nextLine();
String yearOfBirth;
System.out.print("Enter your Year of Birth: ");
yearOfBirth = userInput.nextLine();
StringBuilder concertId = new StringBuilder();
concertId.append(yourName);
concertId.append(yearOfBirth);
concertId.append(generateNumber());
System.out.println(concertId.toString());
}
}
public static int generateNumber()
{
int number = 0;
Random random = new Random();
number = random.nextInt(1, 10);
return number;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your salary per hour: ");
int salary = input.nextInt();
System.out.print("Enter number of hours: ");
int hours = input.nextInt();
int sum = salary * hours;
if (hours == 0) {
System.out.println("Stop!");
break;
}
System.out.println("Total salary " + sum);
}
}}
I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.
Your code does exactly what you tell it to do.
You tell it to:
first ask for TWO numbers
to then compare the first number, and stop on 0
So, the solution is:
ask for one number
compare the number, stop on 0
ask for the second number
If you want to exit whenever you type 0, then you have to check every value after its input.
There is the code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What's your salary per hour? ");
int salary = scanner.nextInt();
if (salary == 0)
exit();
System.out.print("How many hours did you worked today? ");
int hours = scanner.nextInt();
if (hours == 0)
exit();
int sum = salary * hours;
System.out.println("Your total salary is " + sum);
}
}
private static void exit() {
System.out.println("Have a nice day!");
System.exit(0);
}
Please write a comment if that doesn't match your expectation
I know that the question has been asked but I tried to apply what I saw here and got an error.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
// If the input isn't an int, the loop is supposed to run
// until an int is input.
get_input.hasNextInt();
year_of_birth = get_input.nextInt();
}
//year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
Without the loop, everything works fine. What is wrong in my code? To be clear, I'm trying to ask for an input until the input can be validated as an integer.
Thanks a lot in advance.
If you would like to skip invalid non-int values, your loop should look like this:
while (!get_input.hasNextInt()) {
// skip invalid input
get_input.next();
}
// here scanner contains good int value
year_of_birth = get_input.nextInt();
This works for me if i understood you correctly. You need to keep checking what value has the scanner, so you need to keep advancind through the scanner while the value is not an integer:
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) { //check if it is not integer
System.out.println("Enter your year of birth"); // ask again
get_input.next(); //advance through the buffer
}
year_of_birth = get_input.nextInt(); //here you get an integer value
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
Given my program below, I am a little confused about what the return line actually does in a method. No matter what variable I put there, it still returns the same values when I call the method in my main class. What exactly does using the return (variable name) do in any method that is not a void? Are you supposed to list a return statement for each variable in your method header? Sorry I'm just trying to really understand methods. Also, can you please critique my overall program. Does it make sense? Does it seem well written? Thank you!
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int seconds=0, minutes=0, hours=0, days=0;
System.out.println("We will convert seconds to minutes hours and days!");
System.out.println("How many conversions would you like to do?");
Scanner keyboard = new Scanner(System.in);
int conversion =keyboard.nextInt();
for (int count = 1; count <= conversion; count++)
{
Calculator.convert();
}
}
public static void convert()
{
System.out.println("Enter seconds: ");
Scanner keyboard = new Scanner(System.in);
double seconds, minutes, hours, days;
seconds = keyboard.nextInt();
minutes = seconds/60.0;
hours = minutes/60.0;
days = hours/24.0;
System.out.println("Minutes: " + minutes + " Hours: " + hours + " Days: " + days);
}
}
You don't need to use a return in your method because you don't use it. Returns are used to return a value to the program that called a function. For exemple, if you want to have back the "days" value, you should call the method like this :
double days = Calculator.convert(seconds, minutes, hours, days);
But if you don't need to become back in your program a value generated by the method, your method should return nothing. Nothing is specified with the keyword "void". For example :
public static void convert(double seconds, double minutes, double hours, double days)
{
System.out.println("Enter seconds: ");
Scanner keyboard = new Scanner(System.in);
seconds = keyboard.nextInt();
minutes = seconds/60.0;
hours = minutes/60.0;
days = hours/24.0;
System.out.println("Minutes: " + minutes + " Hours: " + hours + " Days: " + days);
}
I'm doing a homework assignment in my Java class. I got most of it except for this one part about elapsed time. We have to use methods. Here's the assignment and the code I have.
"You have just been hired by a company to do it’s weekly payroll. One of the functions you must perform daily is to check the employee time cards and compute the elapsed time between the time they “punch in” and “punch out”. You also have to sometimes convert hours to minutes, days to hours, minutes to hours and hours to days. Since you’ve just finished your first programming class you decide to write a program that will help you do your job.
You decide to structure your program the following way. The main function will just be a menu that the user can select from to get the information they want. Each option on the menu will call a specific method(s) to solve the task and/or output the answer.
You may assume for this program that all elapsed times will be in a single day but the others may span much further. Be sure to provide sufficient test data to demonstrate that your solutions are correct. (show at least one output for each conversion [probably several for option #5]). "
import java.util.*;
public class Prog671A
{
public static void hoursToMinutes()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter hour(s): ");
int hours = input.nextInt();
System.out.println(hours + " * 60 = " + (hours * 60) + " minutes.");
System.out.println("");
}
public static void daysToHours()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter day(s): ");
int days = input.nextInt();
System.out.println(days + " * 24 = " + (days * 24) + " hours.");
System.out.println("");
}
public static void minutesToHours()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter minute(s): ");
int minutes = input.nextInt();
System.out.println(minutes + " / 60 = " + ((double)minutes / 60) + " hours.");
System.out.println("");
}
public static void hoursToDays()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter hour(s): ");
int hours = input.nextInt();
System.out.println(hours + " / 24 = " + ((double)hours / 24) + " days.");
System.out.println("");
}
public static void elapsedTime()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the beginning hour: ");
int startingHour = input.nextInt();
System.out.print("Enter the beginning minute(s): ");
int startingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String startingAmOrPm = input.nextLine();
System.out.print("Enter the ending hour: ");
int endingHour = input.nextInt();
System.out.print("Enter the ending minute(s): ");
int endingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String endingAmOrPm = input.nextLine();
System.out.println("");
System.out.println("The elapsed time is: " + );
}
public static void main (String args [])
{
int x = 1;
while (x == 1) {
Scanner input = new Scanner (System.in);
System.out.println("Conversion Tasks");
System.out.println("\t1. Hours -> Minutes");
System.out.println("\t2. Days -> Hours");
System.out.println("\t3. Minutes -> Hours");
System.out.println("\t4. Hours -> Days");
System.out.println("\t5. Elapsed time between two times");
System.out.println("\t6. Exit");
System.out.print("Enter a number: ");
int menu = input.nextInt();
System.out.println("");
if (menu == 1)
hoursToMinutes();
if (menu == 2)
daysToHours();
if (menu == 3)
minutesToHours();
if (menu == 4)
hoursToDays();
if (menu == 5)
elapsedTime();
if (menu == 6)
x = 0;
}
}
}
I just need help here
public static void elapsedTime()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the beginning hour: ");
int startingHour = input.nextInt();
System.out.print("Enter the beginning minute(s): ");
int startingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String startingAmOrPm = input.nextLine();
System.out.print("Enter the ending hour: ");
int endingHour = input.nextInt();
System.out.print("Enter the ending minute(s): ");
int endingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String endingAmOrPm = input.nextLine();
System.out.println("");
System.out.println("The elapsed time is: " + );
}
Just convert the start and end times to minutes since the start of the day (at midnight). For p.m., just add 12 to the hour before converting to minutes. Then subtract and convert back to hours and minutes for the elapsed time.
why do you want to take the hours etc stuff manually??
Read the system date when the User logs in System.currentTimeMillis() store this time somewhere
When the User exists do the same get the System Time. Subtract it from the time you stored initially when the user logged in.
I hope this is what ur looking for ?