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();
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;
}
}
I am working on a java assignment for class. Very basic but just starting to learn programming. The main jist of the assignment is to write a Java program that reads a student name, his/her age, and his/her height (in feet) from the console and prints out all pieces of data related to a student on one line. This is what I have so far but I am getting a few errors.
import java.util.Scanner;
public class assignment1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name = Mike;
int age = 21;
double height = 5.9;
Scanner inReader = new Scanner(System.in);
System.out.println("Mike");
Name = inReader.nextLine("Mike");
System.out.print("21");
age = inReader.nextInt("21");
System.out.println("5.9");
height = inReader.nextDouble ("5.9");
System.out.println ("Mike" + "21" + "5.9");
}
}
You are off track in a few ways.
inReader.nextLine("Mike"); should be inReader.nextLine();. You cannot put something between those brackets in this case.
String Name = Mike; int age = 21;double height = 5.9;
just need to be declared. You want to enter the data in the console, not the code itself.
String Name; int age = 0;double height = 0;
System.out.println("Mike"); is not where you put inputs. Rather, it is where you put prompts that go to the user. You want to ask the user for their input there.
To print the variables in a string, you want to put the variable name in the string like so: System.out.println (height);
The full working code is below, but I encourage you to try and understand how this works. Feel free to ask any questions in the comments below.
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name;
int age = 0;
double height = 0;
Scanner inReader = new Scanner(System.in);
System.out.println("What is their name?");
Name = inReader.nextLine();
System.out.println("What is their age?");
age = inReader.nextInt();
System.out.println("What is their height?");
height = inReader.nextDouble ();
System.out.println (Name + " " + age + " " + " " + height);
}
Here ist a first solution to give you a starting point:
public static void main(String[] args) {
String name ;
int age ;
double height;
Scanner inReader = new Scanner(System.in);
System.out.println("Enter name:");
name = inReader.nextLine();
System.out.println("Enter age:");
age = inReader.nextInt();
System.out.println("Enter height");
height = inReader.nextDouble();
System.out.println ("name: " + name + ", age: " +age + ", height: " + height);
}
The above code will work as long as you enter valid input. Try it. Then input something invalid (for example a char for age)
I'm trying to learn the basics of Java when I have nothing to do at work, and I wanted to play around with input. This is what I have now:
import java.util.Scanner;
public class Input {
private static Scanner input;
public static void main(String [] args){
String name = (askName());
double age = (askAge());
System.out.println("Your name is " + name + " and your age is " + age);
}
static String askName(){
System.out.print("What is your name?");
input = new Scanner(System.in);
//listens for strings
String name = input.next();
return name;
}
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
double age = input.nextDouble();
if (input.hasNextDouble()){
return age;
} else {
System.out.println("Please insert a number:");
askAge();}
}
}
And this is what I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type double
at Input.askAge(Input.java:16)
at Input.main(Input.java:6)
What do I do to force the user to enter an integer (that is, how do I make the method repeat itself until it gets an int that it can return?)
Return the value of the recursive call:
System.out.println("Please insert a number:");
return askAge();
However: it would be better to use a loop rather than recursion here, since you could (eventually) get a StackOverflowError if you keep on entering an invalid value.
If condition is used for decision making and not for looping.
Use a while loop , Break the loop when u get the correct value.
I am wiring a sudo code.
while(true){
if (input.hasNextDouble()){
//Assign value to a variable ;
//Break loop
} else {
//Re ask question
System.out.println("Please insert a number:");
}
}
Example link for your help.
The exception you are getting is because you are not returning any value from askAge() in else part.
I would rather do it this way:
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String name = getString(sc, "What is your name? ");
int age = getInt(sc, "What is your age? ");
System.out.println("Your name is " + name + " and your age is " + age);
}
/* You increase the performance when using an already existing single
scanner multiple times for different reasons (to get a name, first name,
second name, age, etc.), instead of making a new Scanner each time */
public static String getString(Scanner sc, String message) {
System.out.print(message);
return sc.nextLine();
}
public static int getInt(Scanner sc, String message) {
System.out.print(message);
if (sc.hasNextInt()) {
return sc.nextInt();
} else {
sc.next(); // required to skip the current input
return getInt(sc, "Please insert a number: ");
}
}
Please change your mathod like,
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
if (input.hasNextDouble()){
return input.nextDouble();
} else {
System.out.println("Please insert a number:");
}
return askAge();
}}
My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];
I'm working on a programming project for my intro class. I have a code that I'm trying to compile, but I'm having a hard time getting it to work after I added the PrintWriter. All was running well until I tried to print to a text file. Can someone help me figure out how to get it to run?
(Also, if you find any errors in my logic/layout/whatever, try to contain it! I still want to debug the program myself, I just can't do that until it runs :)
Attempt: (so far)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
Should be outside (before) the while loop. Having it inside the loop means it is not in the scope of your other uses of outputFile after the while loop.