Why does the input not print out - java

I just want it to display my name. It worked in a different code but I cut out the parts that were supposed to say the name.
import java.util.Scanner;
public class ComputePay
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name;
System.out.print("Please enter your First and Last name >> ");
input.nextLine();
name = input.nextLine();
System.out.println("Thank you, " + name);
}
}

When you do your input.nextLine(); for the first time, you don't save the result to any variable. So you are loosing the value that the user entered before.
If you just remove that line then name = input.nextLine(); will successfully read the value and store it in the variable name.
If you want to read in multiple values just repeat that process:
System.out.print("Please enter your first name >> ");
firstName = input.nextLine();
System.out.print("Please enter your last name >> ");
lastName = input.nextLine();

Related

I have to enter a first name, last name, student id, and avg and have it displayed on a line separated by commas on a new csv file. How do I do this?

Here is my updated code. Again, the instructions are as follows: "Enter a first name, last name, student id, and avg, then have those 4 things displayed in a new csv file, with each of the 4 inputs separated by a comma in each record." This code works well, is there anything I can do better? Also, is "in.close()" necessary in this case since I am not reading a file, but rather user input?
public class Homework07 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
String newRecord = (firstName + ", " + lastName + ", " + studentId + ", " + currentAvg);
outFile.println(newRecord);
}
in.close();
outFile.close();
}
}
your code capture the enter key entered by user to I added an empty in.nextLine(); to escape it, and secondly I added outFile.flush(); to flush the stream to the file.
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
outFile.write(firstName + "," + lastName + "," + studentId + "," + currentAvg);
outFile.flush();
}
in.close();
outFile.close();
Your call to the Scanner#nextDouble() method does not consume the ENTER key hit (the newline character) therefore you need to do it yourself by placing this line: in.nextLine(); directly under this line:
double currentAvg = in.nextDouble();
Ironically, you need to apply a newline character when you write to your file for every record you want to save, like this:
String record = new StringBuilder(firstName).append(", ").append(lastName)
.append(", ").append(studentId).append(", ")
.append(currentAvg).append(System.lineSeparator())
.toString();
outFile.write(record);

java do while asked for input twice

why do I need to input 2 times? please help I'm new to java, can't find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed the do while but it still asks for the second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
I have updated your code. This will work for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output :
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Explanation : If you are giving valid data, then the loop will continue to take inputs (not taking inputs twice). As soon as, you give invalid data, then, the code will prompt you to enter the valid data and loop will stop executing as you made valid = false.
The reason why it asks you for input twice is due to you in.hasNextInt() which will check your scanner for input from the system. Since your system does not have any input due to you calling age = in.nextInt(); which will move the scanner to the next word before your in.hasNextInt(), The function in.hasNextInt() will require you to input something so that it can validate if it is an Int or not.
what we want to do, is to first check the current scanner's input if it has an integer before we either store it inside age or loop again and ask for new input.
A better way of checking would be to do something like this.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = 0;
System.out.println("Enter your age: ");
while(!in.hasNextInt()){// checks if scanner's next input is an int, return true if next input is not an Int and the while loop continues till the next input is an Int
System.out.println("Please enter a valid age: ");
in.nextLine();//move the scanner to receive the next nextLine
//this is important so the hasNextInt() wont keep checking the same thing
}
//it will only exit the while loop when user have successfully enter an interger for the first word they inputted.
age = in.nextInt();
System.out.println("Your age is: " + age);
}
}
Output:
Enter your age:
boy
Please enter a valid age:
boy girl
Please enter a valid age:
5
Your age is: 5
Hi : D there is becuase of the !in.hasNextInt() it will cause you need to do the input again but you can change it to other condition like if the age is bigger than certain value.
public class stackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age =0 ;
boolean valid = false;
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(age>90) {
System.out.println("Please enter a valid age");
valid=true;
}
else valid=false;
}while(valid);
System.out.println("Age: " + age);
}
}
You should move the System.out.println("Enter your age: "); statement outside the do-while loop.

Scanner doesnt read input in else statement

Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).

Using multiple user inputs and printing into a single line

I'm trying to get 3 different inputs from a user and then print them onto a single line, to get an end result of something like "The cow jumped over the moon." I'm brand new to Java and don't quite understand how to print these variables properly. Could anyone help?
import java.util.Scanner;
public class test_input {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first noun: ");
String n = scan.nextLine();
System.out.println("Enter the second noun: ");
String a = scan.nextLine();
System.out.println("Enter a verb: ");
String v = scan.nextLine();
System.out.println("The" +n +v "over the" +a);
}
}

Java ask String input with multiple words

HI I am having problem with asking Direct Whole name using Java.
System.out.println("DOCTOR");
System.out.println("Enter ID Number:");
idnumber = scan.next();
System.out.println("Enter Name");
name = scan.next();
System.out.println("Enter Field of Specialization:");
field = scan.next();
System.out.println("ID " + idnumber);
System.out.println("Name " + name);
System.out.println("Specializtion " + field );
and When I enter this information below:
ID = 100 Name = Brandon Sullano
it gives me this result
ID 100
Name Brandon
Specializtion Sullano
I want Name to be dynamic so I can Input even two words how to do it?
Thanks in Advance..
Try this code:
import java.util.Scanner;
public class DoctorDoctor {
public static void main (String [] args) {
int idnumber;
String name, field;
Scanner sc = new Scanner(System.in);
System.out.println("DOCTOR");
/** Assuming ID number is an integer value */
System.out.print("Enter ID Number: ");
idnumber = sc.nextInt();
sc.nextLine(); // This is important, for clearing the new line character
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter Field of Specialization: ");
field = sc.nextLine();
System.out.println();
System.out.printf("%-15s: %d%n", "ID Number", idnumber);
System.out.printf("%-15s: %s%n", "Name", name);
System.out.printf("%-15s: %s%n", "Specialization", field);
sc.close();
}
}
Example input/output:
DOCTOR
Enter ID Number: 100
Enter Name: Brandon
Enter Field of Specialization: Heart Surgeon
ID Number : 100
Name : Brandon
Specialization : Heart Surgeon
Use:
name = scan.nextLine();
Also, if the ID number is an integer, use nextInt() (make sure to also declare idnumber as an int instead of string)
Fixed code:
System.out.println("DOCTOR");
System.out.println("Enter ID Number:");
idnumber = scan.nextInt();
scan.nextLine();
System.out.println("Enter Name");
name = scan.nextLine();
System.out.println("Enter Field of Specialization:");
field = scan.nextLine();
System.out.println("ID " + idnumber);
System.out.println("Name " + name);
System.out.println("Specializtion " + field );
Using just next() will take all input before a space. nextLine() will take all input before return is pressed.
More on Scanner here
Pro tip: In most cases you'll use scan.nextLine() rather than scan.next() so you may want to get into the habit of using it.
Since you say scan.nextLine() "doesn't work", I suggest using BufferedReader.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
//in your code:
int idnumber = Integer.parseInt(br.readLine());
String name = br.readLine();
String field = br.readLine();
You have to import java.io.BufferedReader and java.io.InputStreamReader

Categories

Resources