Methods' outputting twice with arrays - java

I have to basically make a program that would add a name given a prompt and place it in the array. It should do the same for the age of the person. I have been forced to do this with methods. The only issue i am having is that with the 3rd last line, the name get's asked twice. I don't know how to fix that. Any help is appreciated.
public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {``
System.out.println("Please input the age of " + names[x]);
Scanner age = new Scanner(System.in);
int a1 = age.nextInt();
holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
String holdername[] = new String[q2];
for (int x = 0; x<q2;x++) {
System.out.println("Please input the name of the person");
Scanner name = new Scanner(System.in);
String n1 = name.nextLine();
holdername[x]=n1;
}
return holdername;
}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
output(nameinput(q1),ageinput(nameinput(q1),q1));
}
}

In output(nameinput(q1),ageinput(nameinput(q1),q1)); you call the method nameinput twice, so the code also will be executed twice.
You could ask the names in nameinput, store them into an array and pass that array to ageinput.

#Aadithya Gowthaman, try this one in your editor.
package com.aamir;
import java.util.Scanner;
public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {
System.out.println("Please input the age of " + names[x]);
Scanner age = new Scanner(System.in);
int a1 = age.nextInt();
holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
String holdername[] = new String[q2];
for (int x = 0; x<q2;x++) {
System.out.println("Please input the name of the person");
Scanner name = new Scanner(System.in);
String n1 = name.nextLine();
holdername[x]=n1;
}
return holdername;
}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
String [] namesArray = nameinput(q1);
int [] ageArray = ageinput(namesArray, q1);
output(namesArray, ageArray);
}
}

Related

How to close Scanner opened in a method JAVA

I started learning JAVA a couple of days ago, so my question might be too basic.
I have created a piece of code which is as follows:
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
Scanner sc = new Scanner(System.in);
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
I want to know where should I write:
sc.close();
Also:
Any other suggestion to code for improvement are Welcome!
You should not close the scanner do not worry about that it will terminated after calculating the simpleInterest. When you run the program and after entering required values it will calculate and return the result and quit.
In you code 1 improvement is you should not create Scanner object again and again there should be only 1 object of Scanner throughout the life cycle.
Below is your updated code -
public class Que01 {
private static Scanner sc = null;
public static void main(String[] args) {
sc = new Scanner(System.in);
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
Create Scanner on start of the program and use it again and again. thats it
hope this will help you.
Thanks to Vince, I was able to create a good version of my code.
and this is the answer I needed.
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle=acceptInt(sc,"Principle");
int roi=acceptInt(sc,"Rate Of Interest");
int years=acceptInt(sc,"Years");
sc.close();
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(Scanner sc,String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}```
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle = acceptInt("Principle", false, sc);
int roi = acceptInt("Rate Of Interest", false, sc)
int years = acceptInt("Years", true, sc);
float si = simpleInterest(principle, roi, years);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1, boolean closeScanner, Scanner sc) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
if (closeScanner)
sc.close();
return i;
}
static float simpleInterest(int p, int r, int yr) {
return p * yr * r / 100;
}
}
i am not sure if this is a good practice of passing boolean as parameter to decide to close scanner
import java.util.Scanner;
public class Que01 {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int principle = acceptInt("Principle");
int roi = acceptInt("Rate Of Interest");
int years = acceptInt("Years");
float si = (p * yr * r/100);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
sc.close();
return i;
}
}
This is what I would say but I'm not an expert. sc.close just saves anything you did with the scanner, eg. writing to a file and saving the file. - thus in this scenario I wouldn't even use it. I also wouldn't use a method to calc the si unless you plan to use it elsewhere as it's just taking up more space

Java using if(search) == with multiple classes giving error search cannot be resolved to a variable

I am trying to use multiple classes with arrays for the first time which interact with each other and I am having trouble getting my program to work.
My intention is in Employee.java you enter the ID and details of an employee through addEmployee(), then run addQual(); which is in Qualification.java which adds qualifications to the employee.
if(search == Employee.idArray)
return;
I am trying to use the above code for addQual(); to retrieve the ID of the employee from Employees.java but it does not work. I get the following error:
Qualification.java [line: 28] Error: search cannot be resolved to a variable
I am stuck at this point and not making much progress help and insight would be greatly appreciated thanks.
Employee.java
import java.util.*;
public class Employee
{
final static int MAX=20;
public static String [] firstnameArray= new String[MAX];
public static String [] lastnameArray= new String[MAX];
public static String [] positionArray= new String[MAX];
public static int [] salaryArray= new int[MAX];
public static int [] idArray= new int[MAX];
public static int count=0;
public static void add(int id, String fname, String lname, String position, int salary)
{
idArray[count] = id;
firstnameArray[count] = fname;
lastnameArray[count] = lname;
positionArray[count] = position;
salaryArray[count] = salary;
++count;
}
public static void addEmployee()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<idArray.length; i++)
{
System.out.println("Enter employee id as an integer");
System.out.print(" (0 to finish): ");
int id = sc.nextInt();
sc.nextLine();
if (id==0)
return;
System.out.println("Enter employee First name");
String fname = sc.nextLine();
System.out.println("Enter employee Last name");
String lname = sc.nextLine();
System.out.println("Enter employee position");
String position = sc.nextLine();
System.out.println("Enter employee yearly salary");
int salary = sc.nextInt();
add(id, fname, lname, position, salary);
}
Qualification.java
import java.util.*;
public class Qualification{
final static int MAX=20;
public static String[] qNamearray = new String[MAX];
public static int[] employeeIdarray = new int[MAX];
public static int[] qDurationarray = new int[MAX];
public static int count = 0;
public static void add(int employeeId, String qName, int qDuration)
{
employeeIdarray[count] = employeeId;
qDurationarray[count] = qDuration;
qNamearray[count] = qName;
++count;
}
public static void addQual()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<employeeIdarray.length; i++)
{
System.out.println("Enter employee id as an integer");
System.out.print(" (0 to finish): ");
int employeeId = sc.nextInt();
sc.nextLine();
if(search == Employee.idArray)
return;
System.out.println("Enter employee qualification");
String qName = sc.nextLine();
System.out.println("Enter employee qualification duration");
int qDuration = sc.nextInt();
add(employeeId, qName, qDuration);
}
if(search == Employee.idArray)
return;
The above code does not seem to be doing any useful logical branching (it just exits from the method without any logging/message which is not recommended). Also, there is no search variable declared, hence the error.
I would advice removing this code block and re-running the method.

Java: How to change Class1 variables with Class2 variables

So my project is to make a small poker game that will ask users their name, how many players, and your bets.
However before all this, we need to ask the player if they would like to play a NEW game or a SAVED game. The saved game can be hard-coded.
I created a class1 game, and for the saved game file, I created class2. I want class2 to replace the values of class1 but I am not sure how to do this.
The issue is the values of CLASS1 are NOT being replaced by the values of CLASS2 when we call CLASS2. How can I get the variables from CLASS1 to update to CLASS2?
My First Class:
public class NoC2_Musick extends savedGame
{
public static void main(String[] args)
{
savedGame obj = new savedGame();
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
System.out.println("Is this a NEW Game or a PREVIOUS game?");
System.out.println("How many players will join this game?");
int totalPlayers = input.nextInt();
String[] players = new String[totalPlayers];
obj.oldsavedgame();
System.out.println("What is your name and club?");
for (int i = 0; i < totalPlayers; i++) {
players[i] = inputString.nextLine();
}
System.out.println("These are the Players: ");
for (int i = 0; i < totalPlayers; i++) {
System.out.println(players[i]);
}
System.out.println("Place your Bet.");
int bet = input.nextInt();
}
}
My Second Class:
public class savedGame
{
public int oldsavedgame()
{
int totalPlayers = 3;
String[] players;
players = new String[3];
players[0] = "Sofia";
players[1] = "Shawn";
players[2] = "Tomi";
int bet = 100;
System.out.println("Test");
return totalPlayers;
}
public static void main(String[] args)
{
}
}
I think you are missing some key things here. I do not think you should create a new class for storing the old info.
Just write a method that loads the data into instance variables.
Also, you are not reading the answer to the question: is this a new game / previous.
I would do something along these lines (note: It is not complete, but it should get you headed in the right direction, as far as loading a previous game):
public class NoC2_Musick {
int totalPlayers = 0;
ArrayList<String> players = new ArrayList<String>();
int bet = 0;
private void LoadSavedGame() {
totalPlayers = 3;
players.add("Sofia");
players.add("Shawn");
players.add("Tomi");
bet = 100;
}
public NoC2_Musick() {
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
System.out.println("Is this a NEW Game? (y/n)");
char newGame = input.next().charAt(0);
if(newGame == 'y')
{
System.out.println("How many players will join this game?");
totalPlayers = input.nextInt();
for (int i = 0; i < totalPlayers; i++) {
System.out.println("What is your name and club?");
players.add(inputString.nextLine());
}
}
else {
LoadSavedGame();
}
System.out.println("These are the Players: ");
for (int i = 0; i < totalPlayers; i++) {
System.out.println(players.get(i));
}
System.out.println("The current bet is: " + bet);
System.out.println("Place your Bet.");
int bet = input.nextInt();
}
public static void main(String[] args) {
new NoC2_Musick();
}
}

How to fix my Array class

I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.

Java: The constructor gerbil(int) is undefined

So I've read over all of the constructor undefined posts on stackoverflow and tried the solutions and they haven't worked for me. Maybe I'm trying it wrong. I keep getting "the constructor Gerbil(int) is undefined."
The code that's the problem:
GerbilArray[i] = new Gerbil(i);
My full code:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(i);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
}
}
}
}
Also you've probably seen that my nested for-loop isn't finished as well. I'm trying to make an array inside of an object that will store "x" amount of integers inside of my object listed from the user (int totalFood) but I have no idea how.
You don't have a constructor Gerbil(int a) in the class Gerbil and you try to call it!
Just call it this way:
GerbilArray[i] = new Gerbil();

Categories

Resources