I've been working on this for a while but can't seem to get it. I need to store user input into an array from another object but I can't get it to work. I'm not sure if its my constructor or I'm missing something but any help is appreciated
Here is the output program
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
Polygon ps;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps = new Polygon(side);
}
ps = new Polygon(side);
Here is the constructor of the other class
public class Polygon {
protected int[] sideLengths;
public Polygon(int sides){
sideLengths= new int[sides];
}
you need to do
ps=new Polygon(numSides+1); //adding 1 because for-loop starts with index 1
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps[i]=side;
}
by this what we do is assign the 'side' value entered by user to a particular index in array.
hope this helps!
Good luck
The way I understand your Program I think you are looking for this kind of logic
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side = 0;
Polygon ps;
int sideLengths[] = new int[numSides];// array to store length of polygon of sides `numSides`
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
sideLengths[i-1] = sc.nextInt();// creating array to store lengths
}
ps = new Polygon(sideLengths);// generating your pollygon by sending the array
}
And you Polygon class should look like this
class Polygon {
protected int[] sideLengths;// storing the lengths of all sides
public Polygon(int dimensions[]) {
sideLengths = dimensions ;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if(in.equalsIgnoreCase("p")) {
Integer sides[];
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
if(numSides>0){
sides = new Integer[numSides];
}
Polygon ps;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
sides[i] = side;
}
ps = new Polygon(sides);
}
}
public class Polygon {
private Integer[] sides;
public Polygon(Integer[] sides){
this.sides = sides;
}
}
Now we have created an array of size of sides and array is been passed as an argument to constructor for initializing Polygon's object
it should be like
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
Polygon ps = new Polygon(numSides);
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps.addSide(side, i-1);
//ps = new Polygon(side);
}
//ps = new Polygon(side);
}}}
and Polygon class like
public class Polygon {
protected int[] sideLengths;
public Polygon(int sides){
sideLengths= new int[sides];
}
public void addSide(int side, int index){
sideLengths[index] = side;
}
}
You are calling the constructor correctly, but after for loop ends you are again creating a new instance of Polygon and assigning it to ps. Either create an array of int or ArrayList of Integer, and store each instance of Polygon side length in that just before the for loop ends.
ArrayList<int> psListpsSideLengthList = new ArrayList<int>;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
psListpsSideLengthList.add(side);
}
Related
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();
}
}
Input and storing Strings in multi-dimensional arrays with user-input
i have learned multidimensional array from google, it was easy to learn but when i have to implement in any scenerio! its difficult to handle it. i have declared multi-dimensional array using user input and now i want to declare this array in table . how?
import java.util.Scanner;
public class RugbyProject{
final static int RESULT_POINTS_WIN = 2;
final static int RESULT_POINTS_DRAW = 1;
final static int RESULT_POINTS_LOSS = 0;
final static int GAME_POINTS_TRY = 5;
final static int GAME_POINTS_PENALTY = 3;
final static int GAME_POINTS_DROP_GOAL = 3;
final static int GAME_POINTS_CONVERSATION = 2;
public class Stats {
// TODO Auto-generated method stub
int wins;
int draws;
int losses;
int tries;
int penalties;
int dropgoals;
int conversation;
int totalResultPoints = (wins * RESULT_POINTS_WIN) + (draws * RESULT_POINTS_DRAW) + (losses + RESULT_POINTS_LOSS) + (tries * GAME_POINTS_TRY) +
(penalties * GAME_POINTS_PENALTY) + (dropgoals * GAME_POINTS_DROP_GOAL) + (conversation * GAME_POINTS_CONVERSATION) ;
int averageScorePerMatch = (totalResultPoints/5);
}
public static void main(String args[]){
String teams[] = {"Ireland","England","Scotland","Brazil","Irelan","Romania","Germany"};
System.out.println("Welcome to the six nation ChampionShip");
for(String element : teams){
System.out.println("Enter number of wins, draws and losses for " + element);
Scanner myScanner = new Scanner(System.in);
int [] integer = new int[3];
for(int i = 0; i<3; i++){
integer[i] = myScanner.nextInt();
}
System.out.println("ENter total try count, total penalty count ," + " total dropgoal count total conversation count for " + element);
Scanner myScanner2= new Scanner(System.in);
int[] integers2 = new int[3];
for(int i=0; i<3; i++){
integers2[i] = myScanner2.nextInt();
}
}
}
}
So far, I'm just trying to get the input and store it.I am new in java so i am not good in programming
Thats the answer to print array in table
public static void main(String args[]){
String teams[] = {"Ireland","England"};
int [] integer ={};
int[] integers2 ={};
int a=0; int b=3;
System.out.println("Welcome to the six nation ChampionShip");
integer = new int[6];
integers2 = new int[6];
Scanner myScanner = new Scanner(System.in);
for(String element : teams){
System.out.println("Enter number of wins, draws and losses for " + element);
//Scanner myScanner = new Scanner(System.in);
System.out.println("a="+a +" b="+b);
for(int i = a; i<b; i++){
integer[i] = myScanner.nextInt();
}
System.out.println("ENter total try count, total penalty count ," + " total dropgoal count total conversation count for " + element);
//Scanner myScanner2= new Scanner(System.in);
for(int i=a; i<b; i++){
integers2[i] = myScanner.nextInt();
}
a=3;
b=6;
}
System.out.println("Team \tP \tW \tD \tL \t");
for(int j=0; j<teams.length; j++){
//
if(j==0){
System.out.println(teams[j]+"\t"+(integer[j]+integer[j+1]+integer[j+2])+"\t"+integer[j]+"\t"+integer[j+1]+"\t"+integer[j+2]);
}else{
System.out.println(teams[j]+"\t"+(integer[j+2]+integer[j+3]+integer[j+4])+"\t"+integer[j+2]+"\t"+integer[j+3]+"\t"+integer[j+4]);
}
}
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.
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);
}
}
import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();