Array Guessing game - How to set and get an array? - java

I am trying to create a guessing game where the user enters a name and is
prompted to pick a number 5 times. I am trying to store the numbers in an array and use set and get methods to print out the attributes of the array. I have achieved this for the name but I am unable to set and get the array.
import java.util.Scanner;
public class StudentStore
{
private String n1;//store's the player's name
//private int [] s10; //stores the player's score
private int i;
private int noOfPlayers = 5;
private int[] s10 = new int[noOfPlayers];
Scanner kboardIn = new Scanner(System.in);
private int index;
int newInt = 0;
public StudentStore(String n1, int [] s10, int i )
{
this.n1 = n1;
this.s10[i] = s10[i];
this.setName(n1);
//this.i = i;
this.setScore(s10,i);
//this.index = index;
// PlayerScore.incNumberScores();
}
public void setScore( int []s10, int i)
{
//takes an integer score, sets variables and checks topScore
this.s10[i] = s10[i];
//this.checkAndSetTopScore();
}
public int [] getScore()
{
return this.s10;
}
public void setName(String n1)
{
this.n1 = n1;
}
public String getName()
{
return this.n1;
}
}
import java.util.Scanner;
public class StudentTester
{
public static void main(String args[])
{
Scanner kboardIn = new Scanner(System.in);
int noOfStudents;
System.out.print("Enter the number of students: ");
noOfStudents = kboardIn.nextInt();
//int[] noOfStudents;
//noOfStudents = new int[100];
StudentStore[] student1 = new StudentStore[noOfStudents];
//int s1 = 0;
int noOfPlayers = 5;
int[] s10 = new int[noOfPlayers];
//s10 = 0;
String n1 = "something";
int i = 0;
for (int index = 0; index < student1.length; index++)
student1[index] = new StudentStore(n1, s10, i);
for (int index = 0; index <= student1.length; index++)
{
System.out.print("What is name of student no "+(index+1)+" ?");
n1 = kboardIn.next();
student1[index].setName(n1);
System.out.print("What is mark for student no "+(index+1)+" ?");
for(i=0; i < noOfPlayers; i++)
{
s10[i] = kboardIn.nextInt();
student1[index].setScore(s10, i);
System.out.println("This is it" + s10[i]);
}
System.out.println(student1[index].getScore( ));
System.out.println(student1[index].getName());
System.out.println(index);
System.out.println(s10[index]);
System.out.println(i);
//System.out.println(s10[]);
}
for (int index = 0; index < student1.length; index++)
System.out.println("\nTotal Mark for " + student1[index].getName()+ " is\t" + student1[index].getScore());
}
}

It seems like you want to know how to loop over arrays. This is how you could achieve it:
String[] strings = {"hi","yo","test"};
for(String s : strings){
System.out.println(s);
}

System.out.println(student1[index].getScore()); you are getting the array, but printing an array will not give stored values in array. You should iterate over the array and print seperatly all values.

Thanks for the reply's. In the program System.out.println(student1[index].getScore()) is not printing a number. It is printing [I#137c6OD. I am not sure how to iterate over the array, but I will look up how to do it. Thanks a lot

Related

Using an array to input strings, and another one to output word frequency

So I am trying to complete this code. The goal is to input an array of strings, then count the frequency of how often the words are found. For example:
input:
joe
jim
jack
jim
joe
output:
joe 2
jim 2
jack 1
jim 2
joe 2
An array must be chosen for Strings, and another array much be chosen for word frequency.
My code so far:
I am stuck into trying to implement this. The string method is set, but how am I going to count the frequency of words, and also assign those values to an array. Then print both side by side. I do know that once the integer array is set. We can simply do a for loop to print the values together such as. System.out.println(String[i] + " " + countarray[i]);
public class LabClass {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int freq = 0;
for (int i = 0; i < listSize; i++) {
if (wordsList[i].compareTo(currWord) == 0) {
freq++;
}
}
return freq;
}
public static void main(String[] args) {
LabClass scall = new LabClass();
Scanner scnr = new Scanner(System.in);
// assignments
int listSize = 0;
System.out.println("Enter list Amount");
listSize = scnr.nextInt();
// removing line to allow input of integer
int size = listSize; // array length
// end of assignments
String[] wordsList = new String[size]; // string array
for (int i = 0; i < wordsList.length; i++) { //gathers string input
wordsList[i] = scnr.nextLine();
}
for (int i = 0; i < listSize; i++) {
String currWord = wordsList[i];
int freqCount = getFrequencyOfWord(wordsList, listSize, currWord);
System.out.println(currWord + " " + freqCount);
}
}
}
int some_method(String[] arr, String word) {
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (arr[i].equals(word)) count++;
}
return count;
}
Then in main method:
String[] array = ["joe", "jake", "jim", "joe"] //or take from user input
int[] countArray = new int[array.size()]
for (int i=0; i<array.size(); i++) {
countArray[i] = some_method(array, array[i])
}
System.out.println(array[0] + " " + countArray[0]);
Ouput:
joe 2

Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}

NullPointerException from array created in a method

I'm currently doing a simple university project about the arrays.
In my project I initialize and fill an array by using a method called "setArray", but when the program returns on the main method in which I try to print the array's content, it returns a NullPointerException.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
setArray(in, num);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static void setArray(Scanner in, int[] num)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
num = new int[dim];
System.out.println("Size: " + num.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < num.length ; i++)
{
ran = (int) (Math.random() * var);
num[i] = ran;
System.out.println(num[i]);
}
}
Have a look at this question about whether Java is Pass By Reference
Your code would be better off like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
num = setArray(in);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static int[] setArray(Scanner in)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
int[] numToReturn = new int[dim];
System.out.println("Size: " + numToReturn.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < numToReturn.length ; i++)
{
ran = (int) (Math.random() * var);
numToReturn[i] = ran;
System.out.println(numToReturn[i]);
}
return numToReturn;
}
if you see your code you are declaring a local variable num in your setArray(scanner in,int[] num) method which is not visible in main function nor it is same as that you declared in main function .
The variable array num in the main function is different from that in setArray() function.

I keep getting a line of character as my output for my sum of all years WHY?

Everything that ive done so far is correct, but once i get down to my last print statement i keep getting a string of characters as my answer when i should be getting the sum of all the salaries for the entire array. PLEASE HELP !
my output is
Total money made by person at row 1 is 118943
The total salaries of all individuals is [[I#1540e19d
public class SummerStats
{
private int [][] salaries;
public SummerStats(int numPeople, int numYears)
{
//initialize array
salaries = new int[numPeople][numYears];
java.util.Random r = new java.util.Random();
//fill array
for(int i=0; i<numPeople; i++)
{
for(int j=0; j<numYears; j++)
{
salaries[i][j] = r.nextInt(100000);
}
}
}
public int [][] getSalaries()
{
return salaries;
}
public int getMostMoneyOverYears()
{
int [] tmp = new int[salaries[0].length];
int k = 0;
for(int i=0; i<salaries.length; i++)
{
for(int j=0; j<salaries[i].length; j++)
{
tmp[k] += salaries[i][j];
}
k++;
}
return getMax(tmp);
}
private int getMax(int [] arry)
{
int sal1=0;
int idx=-1;
for(int i=0; i<arry.length; i++)
{
if(sal1 <arry[i])
{
sal1= arry[i];
idx = i;
}
}
return idx;
}
public int getHighestSalary()
{
//find the highest salary in a single year and return of the index
int [][] tmp = new int [salaries.length][2]; //stores salary (row) and the index (col) from the salaries [][]
int max = 0;
int idxtmp = -1;
int p=0;
for(int i=0; i<salaries.length; i++)
{
for(int j=0; j<salaries[i].length; j++)
{
if(max < salaries[i][j])
{
max = salaries[i][j];
idxtmp = j;
}
}
//add max value and its corresponding index to tmp
tmp[p][0] = max;
tmp[p][1] = idxtmp;
p++;
}
//now that we have the max for each person (row) compare salaries in each row
//reset values
max = 0;
idxtmp = -1;
for(int i=0; i<tmp.length; i++)
{
if(max < tmp[i][0])
{
max = tmp[i][0]; //this is the max salary
idxtmp = tmp[i][1]; //this is the index of the salary from the salaries[][]
}
}
return idxtmp;
}
public int getTotalSalary (int person)
{
int totalSalary = 0;
for(int i=0; i<salaries[person].length; i++)
{
totalSalary+=salaries[person][i];
}
return totalSalary;
}
//get total of all salaries
public int getAllSalaries()
{
int sum = 0;
for(int i=0; i<salaries.length; i++)
{
for(int j=0; j < salaries[i].length; j++)
{
sum += salaries[i][j];
}
}
return sum;
}
}
import java.util.Scanner;
public class TestSummerStats
{
public static void main(String [] args)
{
SummerStats ssObj = new SummerStats(2, 3);
int [][] sal = ssObj.getSalaries();
for(int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
System.out.println("Salary at " + i + " " + j + " is $" + sal[i][j]);
}
}
//keep my output looking clean
System.out.println();
System.out.println("Index of the big baller: " + ssObj.getMostMoneyOverYears());
//keep my output looking clean
System.out.println();
System.out.println("Index of the year with the highest salary: " + ssObj.getHighestSalary());
//keep my output looking clean
System.out.println();
//promt the user to enter the person that you want the salary for
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the person you want to know the salary for.");
int person = scan.nextInt();
//keep my code clean
System.out.println();
//print out the amount of money made by the specified person
System.out.println("Total money made by person at row " + person + " is " + ssObj.getTotalSalary(person));
//sum the entire salaries
System.out.println("The total salaries of all individuals is " + ssObj.getSalaries());
}
}
The method getSalaries() is declared and defined thusly:
public int [][] getSalaries() {
return salaries;
}
It is defined to return a two dimensional array, and the result you're seeing is the default toString() returned from such a beast. To get an actual number, your method should return a number, perhaps a double or an int, your choice, and inside the method body, you should iterate through your 2-D array summing up all the salaries.
Judging from the text in the last line, you should change the method call in the last line from ssObj.getSalaries() to ssObj.getAllSalaries().
The "string of characters" you are getting is what happens when you convert an array to a String (either implicitly by concatenating with another string or explicitly by calling toString() on the array).
You're calling the function getSalaries() which returns an array. You should be calling ssObj.getAllSalaries().
The string you're getting is probably a reference to the salaries array object.

Coding using arrays and multiple methods giving me errors and cannot figure out why

This is my code and i had thought i had everything typed out correct:
import java.util.*;
import java.io.*;
public class Proj5 {
public static void main(String[] args)throws IOException{
Scanner s = new Scanner(System.in);
int [] quizKey = {1,1,2,2,1,1,3,2,4,1,3,5,4,1,2};
String [] userAnswers = new String[100];
String [] wid = new String[100];
int [][] userIndividualAnswers = new int[quizKey.length][userAnswers.length];
int [] numCorrect = new int[quizKey.length];
int max;
int min;
int lines=0;
readInText();
s = readInText();
while(s.hasNext()){
String line = s.nextLine();
String[] tokens = line.split(",");
wid[lines] = tokens[0];
userAnswers[lines] = tokens[1];
lines ++;
}// end while loop
int[][] userAnswersInt = new int[quizKey.length][lines];
numCorrect = gradeSingleQuiz(lines, quizKey, userAnswers, numCorrect, userAnswersInt);
double[] percentCorrect = new double[lines];
percentCorrect = percentCorrect(lines, numCorrect, quizKey);
char[] grades = new char[lines];
grades = grade(numCorrect, lines);
displayOutput(wid, lines, numCorrect, grades, percentCorrect);
}//end main
public static Scanner readInText()throws IOException{
Scanner inFile = new Scanner(new File("QuizScores.txt"));
return inFile;
}// end readInText
public static String[] userAnswers(String userAnswers[]){
return userAnswers;
}
public static int[] gradeSingleQuiz(int lines, int quizKey[], String userAnswers[], int numCorrect[], int userAnswersInt[][]){
for (int j=0; j<=lines; j++){
numCorrect[j]=0;
long[] ara = new long[lines];
long[] abc = new long[lines];
ara [j] = Long.parseLong(userAnswers[j]);
for(int p=0; p<userAnswersInt.length; p++){
abc [p] = ara[j]%10;
ara[j] = userAnswersInt[j][p];
}
for(int n=0; n<=quizKey.length; n++){
if(userAnswersInt[j][n]==(quizKey[n])){
numCorrect[j]++;
}
}
}//end for loop
return numCorrect;
}// end gradeSingleQuiz
public static int max(int max, int numCorrect[]){
max = numCorrect[0];
for(int r=1; r<numCorrect.length; r++){
if(numCorrect[r]>max){
max=numCorrect[r];
}
}
return max;
}
public static int min(int min, int numCorrect[]){
min = numCorrect[0];
for(int r=1; r<numCorrect.length; r++){
if(numCorrect[r]<min){
min=numCorrect[r];
}
}
return min;
}
public static char[] grade(int numCorrect[], int lines){
char[] grade = new char[lines];
for (int j=0; j<=lines; j++){
if(numCorrect[j]>=14)
grade[j]='A';
else if((numCorrect[j]>=12)&&(numCorrect[j]<14))
grade[j]='B';
else if((numCorrect[j]>=11)&&(numCorrect[j]<12))
grade[j]='C';
else if ((numCorrect[j]>=9)&&(numCorrect[j]<11))
grade[j]='D';
else
grade[j]='F';
}
return grade;
}//end grade
public static double[] percentCorrect(int lines, int numCorrect[], int quizKey[]){
double[] centCorrect = new double[100];
for (int j=0; j<=lines; j++){
centCorrect[j] = numCorrect[j]/quizKey.length;
}
return centCorrect;
}
public static void averageScore(int lines, double percentCorrect[]){
double add=0;
for(int d=0; d<=lines; d++){
add = percentCorrect[d] + add;
}//end for loop
System.out.println("Average: " + add + "%");
}// end averageScore
public static void displayOutput(String wid[], int lines, int numCorrect[], char grades[], double percentCorrect[]){
System.out.println("Student ID # Correct %Correct Grade");
for(int i=0; i<lines; i++){
System.out.println(wid[0] + " " + numCorrect[i] + " " +
(percentCorrect[i]) + " " + grades[i]);
}
}// end display output
}//end class
but when i try and compile and run it it gives me these errors:
Exception in thread "main" java.lang.NumberFormatException: For input string: "112211324135412"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
at Proj5.gradeSingleQuiz(Proj5.java:52)
at Proj5.main(Proj5.java:27)
I was thinking maybe i didn't convert the string of that number to an int correct but looking back at it i think i did, i really just don't know what these errors are. according to eclipse there is nothing wrong with the code until it compiles.
The text i am pulling from is this.
4563123,112211324135412
2312311,222121324135211
2312345,112211324135421
5527687,212111313124412
7867567,111111111111111
the first number is the student id the second number is the answers based on numbers; T=1 F=2 A=1 B=2 etc.
Thanks in advance.
EDIT:
Changed my code above to Long and it fixed those errors but it is now giving me an out of bounds exception of 5 at the line abc [p] = ara[j]%10; i know this isnt my orriginal question but if anyone could tell me why this is i would be very appreciative, i was under the impression that 5 was not out of bounds?
Thanks again
112211324135412 is not an int number, its clearly outta int range(-2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)), try to use Long.parseLong(str) instead.
long[] ara = new long[lines];
ara [j] = Long.parseLong(userAnswers[j]);
"112211324135412" => u can parseInt this string, overflow in int.

Categories

Resources