Java. Scanner requests an additional line but does not print it - java

just entered this community and this is my first question here, so please bear with a noob. I created two classes, first is Student, a basic one with fields, constructor and getters. The second one has the main method, a LinkedList, a multiple-entry Scanner (for...) and two simple methods.
My problem is that despite the fact that the For loop has maximum index 1 (x = 0; x < 2), the Scanner expects a third row input and an enter but does not print the third line. I add the two classes, maybe I made a mistake and I would appreciate your help. Thank you in advance.
public class Student {
private String name;
private String surname;
private int firstMark;
private int secondMark;
private int finalExamMark;
public Student(String name, String surname, int firstMark, int secondMark, int finalExamMark) {
this.name = name;
this.surname = surname;
this.firstMark = firstMark;
this.secondMark = secondMark;
this.finalExamMark = finalExamMark;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getFirstMark() {
return firstMark;
}
public int getSecondMark() {
return secondMark;
}
public int getFinalExamMark() {
return finalExamMark;
}
#Override
public String toString (){
return this.name + " " + this.surname + " got " + this.firstMark + " at English, " + this.secondMark + " at Math and " + this.finalExamMark + " at the final exam.";
}
}
public class StudentMain {
static LinkedList<Student> courseAttend = new LinkedList<>();
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
addStudent();
printList(courseAttend);
}
private static void addStudent() {
for (int x = 0; x < 2; x++) {
String s1 = scanner.nextLine();
String[] split = s1.split("\\s");
courseAttend.add(new Student(split[0], split[1], Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4])));
scanner.nextLine();
}
scanner.close();
}
private static void printList(LinkedList<Student> lista) {
for (Student elem : lista) {
System.out.println(elem);
}
}
}
For example, if I input (without quotes)
"Young John 9 9 9"
"Johnson Anne 8 8 8" and I press enter, the cursor moves to next line and waits another input. Only after that third line and the final enter, the message is displayed but the third line is not shown.

courseAttend should be a List<Student> courseAttend = new ...List<>(); like your methode argument printList(List<Student> students) because both could be also a ArrayList and it is the normal way to in implement variables if they have not to be sepciefied, like in your case.
The loop has two nextLine() but you ignore the second one so you are creating a student and waiting of the next input and not saving the input
When a User has to enter multiple arguments for any given prompt, you can expect to have typos. Your prompt expects the User to enter 5 arguments and they are not even from the same typ on a single line delimited with a whitespace. What if the user accidentally give you an ivalid input like a integer as name or a String as mark.
public class StudentMain {
static List<Student> courseAttend = new LinkedList<>();
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
for (int x = 0; x < 2; x++) {
courseAttend.add(createStudent());
}
scanner.close();
printList(courseAttend);
}
private static Student createStudent(){
System.out.print("name: ");
String name = scanner.nextLine();
System.out.print("surname: ");
String surname = scanner.nextLine();
System.out.print("first mark: ");
int firstMark = scanner.nextInt();
System.out.print("second mark: ");
int secondMark = scanner.nextInt();
System.out.print("final exam mark: ");
int finalExamMark = scanner.nextInt();
return new Student(name, surname, firstMark, secondMark ,finalExamMark);
}
private static void printList(List<Student> students) {
for (Student elem : students) {
System.out.println(elem);
}
}
}

Related

(Java) How can I print an object's information when the object is in an ArrayList? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have an ArrayList in main and I have a class with a constructor inside it and a method to print the data. I add a new object with new information, when called, and adds it to the ArrayList to keep it in one place. What I'm having a hard time is the syntax to print the information. I tried it with a regular array but I need to use ArrayList. I need to be able to get the index of a specific object, and print that object's information. For example, the code below the last couple lines:
import java.util.ArrayList;
import java.util.Scanner;
public class student{
String name;
int age;
int birthYear;
public student(String name, int age, int birthYear){
this.name = name;
this.age = age;
this.birthYear = birthYear;
}
public void printStudentInformation(){
System.out.println(name);
System.out.println(age);
System.out.println(birthYear);
}
}
public class Main{
public static void main(String[] args){
ArrayList listOfObj = new ArrayList();
ArrayList names = new ArrayList();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++){
System.out.println("New Student Information:"); // Three student's information will be saved
String name = sc.nextLine();
int age = sc.nextInt();
int birthYear = sc.nextInt();
student someStudent = new student(name, age, birthYear);
listOfObj.add(someStudent);
names.add(name);
}
System.out.println("What student's information do you wish to view?");
for(int i = 0; i < names.size(); i++){
System.out.println((i + 1) + ") " + names.get(i)); // Prints all students starting from 1
}
int chosenStudent = sc.nextInt(); // Choose a number that correlates to a student
// Should print out chosen student's object information
listOfObj.get(chosenStudent).printStudentInformation(); // This is incorrect, but I would think the syntax would be similar?
}
}
Any help or clarification is greatly appreciated.
You need to change your definition of listOfObj from:
ArrayList listOfObj = new ArrayList();
to:
ArrayList<student> listOfObj = new ArrayList<>();
The first will will create a ArrayList of Object class objects.
The second will create a ArrayList of student class objects.
Few more problems in your code:
Since you are reading name using nextLine, you may need to skip a new line after reading the birth year like:
...
int birthYear = sc.nextInt();
sc.nextLine(); // Otherwise in the next loop iteration, it will skip reading input and throw some exception
...
You select an option for the student to display, but that option is 1 indexed and ArrayList stores 0 indexed, so you should change the line to sc.nextInt() - 1:
int chosenStudent = sc.nextInt() - 1; // Choose a number that correlates to a student
Scanner may throw exception in case you enter, for example, a string instead of an int. So make sure you are handling exceptions properly using try-catch blocks.
You change the ArrayList defination and add toString() in your studen
class.
And to print all the student object insted of using for loop use just
one sop.
EX:-
import java.util.*;
class Student {
private String name;
private int age;
private int birthYear;
public Student() {
super();
}
public Student(String name, int age, int birthYear) {
super();
this.name = name;
this.age = age;
this.birthYear = birthYear;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
#Override
public String toString() {
return "Student [age=" + age + ", birthYear=" + birthYear + ", name=" + name + "]";
}
}
public class DemoArrayList {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
scan.nextLine();
String name = scan.nextLine();
int age = scan.nextInt();
int birthYear = scan.nextInt();
list.add(new Student(name, age, birthYear));
}
System.out.println(list);
}
}
O/P:-
2
joy
10
2003
jay
20
2005
[Student [age=10, birthYear=2003, name=joy], Student [age=20, birthYear=2005, name=jay]]

How do i take input for all the variables at the run time? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have created two files one with having private variables and getters and setters, and other with taking input from the user and displaying the output in the console.
When I execute the program, it runs without error but when the input is given, it takes 3 inputs out of 4.
I am unable to get input for the fourth variable.
File with getters and setters👇
package tryProject;
public class Employee {
private String name;
private int yearJoin;
private int salary;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYearJoin() {
return yearJoin;
}
public void setYearJoin(int yearJoin) {
this.yearJoin = yearJoin;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
File to take input and give output
package tryProject;
import java.util.Scanner;
public class EmployeeInfo {
public static void main(String[] args) {
Employee e = new Employee();
Scanner s = new Scanner(System.in);
System.out.println("Enter details: ");
System.out.println("Name: ");
String input_name = s.nextLine();
e.setName(input_name);
System.out.println(e.getName());
System.out.println("Salary: ");
int input_salary = s.nextInt();
e.setSalary(input_salary);
System.out.println(e.getSalary());
System.out.println("Year of Join: ");
int input_YearJoin = s.nextInt();
e.setYearJoin(input_YearJoin);
System.out.println(e.getYearJoin());
System.out.println("Address: ");
String input_Address = s.nextLine();
e.setAddress(input_Address);
System.out.println(e.getAddress());
}
}
I've tested your program and indeed it prints name, salary and year while it prints an empty line for address. The reason for that is when you give input for "year of join", you type some number and then press "Enter". When you press "Enter" you actually give an input of empty line ("\n") and that's still an input and it's taken for address field. That's why the program doesn't wait for your address line. If you use a debugger you'll notice that. If you change String input_Address = s.nextLine(); to String input_Address = s.next(); and then run your program you'll understand what I mean. However, I don't suggest this as a fix.
I suggest that you add scanner.nextLine(); after reading year of join. This way the program will read the next empty line which was generated by pressing "Enter" key. And then it will read your actual address data.
System.out.println("Year of Join: ");
int input_YearJoin = scanner.nextInt();
e.setYearJoin(input_YearJoin);
System.out.println(e.getYearJoin());
scanner.nextLine();
You can read this post for more insight: Scanner is skipping nextLine() after using next() or nextFoo()?
Try .next() instead of .nextLine().
I would change it for the name too.
I changed your code so it works:
public static void main(String[] args) {
Employee e = new Employee();
Scanner s = new Scanner(System.in);
System.out.println("Enter details: ");
System.out.println("Name: ");
String input_name = s.next(); //changed .nextLine() to .next()
e.setName(input_name);
System.out.println(e.getName());
System.out.println("Salary: ");
int input_salary = s.nextInt();
e.setSalary(input_salary);
System.out.println(e.getSalary());
System.out.println("Year of Join: ");
int input_YearJoin = s.nextInt();
e.setYearJoin(input_YearJoin);
System.out.println(e.getYearJoin());
System.out.println("Address: ");
String input_Address = s.next(); //changed .nextLine() to .next()
e.setAddress(input_Address);
}

Java exception running function listEmployee(): java.util.IllegalFormatConversionException

I'm very new to java and I can't figure out what it is I'm doing wrong, it's properly something really basic, I want to be able to add information about employees and then then display/list that data (id, first name, last name, salary, position etc ) using a menu() method.
Everything compiles and adding employee information with addEmployee() seems to work fine but when running listEmployees() I get the exception: java.util.IllegalFormatConversionException.
I have been playing around with it for a bit but I'm not getting anywhere, any help would be greatly appreciated.
import java.util.*;
public class Employee
{
final static int MAX=20;
static int [] idArray= new int[MAX];
static String [] firstnameArray= new String[MAX];
static String [] lastnameArray= new String[MAX];
static int count=0;
public static void add(int id, String fname, String lname)
{
idArray[count] = id;
firstnameArray[count] = fname;
lastnameArray[count] = lname;
++count;
}
public static void addEmployee()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<idArray.length; i++)
{
System.out.println("Enter your id as an integer");
System.out.print(" (0 to finish): ");
int id = sc.nextInt();
sc.nextLine();
if (id==0)E
return;
System.out.println("Enter your First name");
String fname = sc.nextLine();
System.out.println("Enter your Last name");
String lname = sc.nextLine();
add(id, fname, lname);
}
}
public static void listEmployees()
{
for(int i=0; i<count; ++i)
{
System.out.printf("%-15s %10d \n",idArray[i],firstnameArray[i],lastnameArray[i] );
}
}
public static void printMenu()
{
System.out.println
(
"\n ==Menu==\n" +
"1. Add Employee\n"+
"2. Display Employee\n"+
"3. Quit\n"
);
}
public static void menu()
{
Scanner input = new Scanner(System.in);
int option = 0;
while(option!=3)
{
printMenu();
System.out.println("Please enter your choice");
option = input.nextInt();
switch(option)
{
case 1:
addEmployee();
break;
case 2:
listEmployees();
break;
case 3:
break;
default:
System.out.println("Wrong option");
}
}
}
public static void main(String [] args)
{
menu();
}
}
You are passing a string (lastnameArray[i]) to a numeric format (%10d). You need to first convert the string lastnameArray[i] to an int/long and then pass that value to %10d.
System.out.println(idArray[i] + " " + firstnameArray[i] + " " + lastnameArray[i]);
use this one instaed of your printing statement
The printf function has the wrong arguments passed to it. You should match the format and parameters passed to print them in the same order. Assuming you are passing the correct parameter to be printed, the first parameter should have %d , %s , %s respectively.

object array index value is being overided by the preceding index value

This is an odd situation for me, I just started learning Java OOP.
I made a class looks like this
public class Student {
public static String name;
public static int marks;
public Student(String n, int m){
name = n;
marks = m;
}
public static void printProperties(){
System.out.println("Name = " + name + " , marks = " + m);
}
}
As you can see the constructor accepts two data: name and marks.
in my main method
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].name + ", Marks: " + stu[x].marks);
}
So my output as follows:
Please enter number of students:
2
Please enter name for student #1
tom
Please enter age for student #1
20
Please enter name for student #2
billy
Please enter age for student #2
80
#1 Name: billy, Marks: 80
#2 Name: billy, Marks: 80
It should be:
#1 Name: tom, Marks: 20
#2 Name: billy, Marks: 80
Why is the preceding index value overidding its previous index value?
You code should work absolutely fine, if your Student class looks something like this :
public class Student{
String name;
int marks;
public Student(String name, int marks){
this.name = name;
this.marks = marks;
}
}
EDITED :
This is what Jon Skeet mentioned.
You are using static variables which are class level variables, so they are overridden every time you assign value to them and only the last value is retained.
You need instance variables here.
Do not make your fields static, and let's use private to control access -
public class Student {
private String name; // not static, and use private.
private int marks;
public Human(String n, int m){
name = n;
marks = m;
}
public void printProperties(){ // also should not be static.
System.out.println("Name = " + name + " , marks = " + m);
}
}
Don't use static , simple as that
A static variable belongs to the entire class. It is one variable that is shared among all of the objects. So when you change that variable, it changes it for all the objects.
Instead, define name and marks as instance variables. In other words, remove the static modifier from your variable declarations. An instance variable is unique to each object. Each object has its own copy of an instance variable.
Also, it's good practice to declare name and marks as private. Then create getters and setters for those variables. This hides the implementation.
import java.util.Scanner;
public class Student{
private String name;
private int marks;
public String getName() { //getter
return name;
}
public void setName(String name) { //setter
this.name = name;
}
public int getMarks() { //getter
return marks;
}
public void setMarks(int marks) { //setter
this.marks = marks;
}
public Student(String n, int m){
name = n;
marks = m;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].getName() + ", Marks: " + stu[x].getMarks());
}
scan.close();
}
}

Project on Imputing Weather Data

I keep getting the message
Exception in thread "main" java.lang.NoSuchMethodError: WeatherInput:
method ()V not found
in my client class for this project I'm working on and I'm not sure why, I was wondering if anyone here could see what I'm missing?
Here's my service class:
class WeatherInput
{
private static final String NEWLINE = "\n";
private double temp;
private double tempAverage;
private double tempHigh;
private double tempLow;
private double tempHundred;
public String newCity = new String();
public String city = new String();
public WeatherInput( String city) {
temp = 0;
tempAverage = 0;
tempHigh = 0;
tempLow = 0;
tempHundred = 0;
newCity = city;
}
public void setTemp( double temprature)
{
temp = temp;
}
public void tempCalc(String city)
{
while(!city.equals("*"))
{
city = newCity;
}
while(temp != 0)
{
tempAverage = (temp + temp)/2;
if(tempHigh > temp)
tempHigh = temp;
if(tempLow < temp)
tempLow = temp;
if(temp > 100)
tempHundred = temp;
temp++;
}
System.out.print(tempAverage);
}
public String printString(){
return NEWLINE + "Statistics for: " + newCity + "Average: " + tempAverage + "High: " + tempHigh + "Low: " + "Over 100: "
+ tempHundred + NEWLINE;
}
}
And this is my client:
import java.util.*; //For Scanner and class
//----------------------------------------------------------------------------------
//Class Name: KosmowsiProg2
//Description: This class has one method, the main method
//----------------------------------------------------------------------------------
public class KosmowskiProg2
{
//-------------------------------------------------------------------------------
//Method Name: main
//-------------------------------------------------------------------------------
public static void main(String[] args)
{
//-----------------------Local Constants--------------------------------------
//-----------------------Local Variables--------------------------------------
double newTemp;
//-----------------------Objects----------------------------------------------
Scanner scanner = new Scanner(System.in);
String city = new String();
String inputCity = new String();
WeatherInput input = new WeatherInput();
WeatherInput input2 = new WeatherInput();
//---------------------Method Body--------------------------------------------
System.out.print("Please enter the names of the cities, ending in a *");
inputCity = scanner.next();
System.out.print("Please enter the tempratures, ending in a 0");
newTemp = scanner.nextDouble();
input.setTemp(newTemp);
input.tempCalc(inputCity);
}//End main method
private static void printResults(WeatherInput in){
System.out.print(in.printString());
}
}//End class KosmowskiProg2
I'm creating a service class that I can then pass to a client class that will read a list of cities that ends in a "*" and then for each city read a list of tempratures that ends with a "0". It then has to calculate the average temperature, highest and lowest, and then output them along with any temperatures over 100. I've talked to my professor and she told me that the solution is a nested while loop, and that the prompts for the final program should be in a separate client class. I also need to output the totals for each category. The thing is, I'm having a lot of trouble trying to figure out how to use this service class I've created in the client to get the data I need. My professor can't seem to explain it in a way I can understand, so I'm hoping for some help.
WeatherInput requires a String as part of it's constructor...
public WeatherInput( String city)
But you're trying to insansiate it with out any...
WeatherInput input = new WeatherInput(); // This is bad, must have a String value...
If you have your service class in a different file, you need to make sure it's declared public.
public class WeatherInput
{
... etc
}
If you don't you may not be able to access the constructor in the other file.
EDIT: Oh, i just noticed, you don't have a default constructor (one with no arguments), which is why it throws the NoSuchMethodError exception. Your only constructor needs a city name:
public WeatherInput(String city) {
... etc
}
You'll need to declare your classes after you have the city names:
// WeatherInput input = new WeatherInput();
// WeatherInput input2 = new WeatherInput();
//---------------------Method Body--------------------------------------------
System.out.print("Please enter the names of the cities, ending in a *");
inputCity = scanner.next();
System.out.print("Please enter the tempratures, ending in a 0");
newTemp = scanner.nextDouble();
WeatherInput input = new WeatherInput(inputCity);
input.setTemp(newTemp);
input.tempCalc(inputCity);
Or create a constructor that doesn't take any arguments:
public WeatherInput() {
temp = 0;
tempAverage = 0;
tempHigh = 0;
tempLow = 0;
tempHundred = 0;
newCity = null;
}

Categories