Displaying Multidimensional Arrays in Java - arrays

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class JavaClass {
public static void main(String[] args) {
// Things start here
int[][] multi = new int[5][10];
for(int p = 1; p < 5; p++)
{
for(int h = 1;h < 10;h++)
{
System.out.println("Enter the score for Player " + String.valueOf(p) + ", Hole " + String.valueOf(h) + " :");
String v = stringReader();
multi[p][h] = Integer.parseInt(v);
System.out.println(String.valueOf(v));
}
}
}
public static String stringReader()
{
String value;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
value = bufferedReader.readLine();
} catch (IOException e) {
value = "0";
}
return value;
}
Hello! I am currently working on a project for my Grade 12 Computer Science course where i am asked to make a "Golf Score Tracker" the description of the project is (add to the code below code that calculates and displays each golfers individual score)
I've tried working with while loops however whatever I do it does not seem to display. My teacher is also stuck lol he is actually the reason I am here asking for help on this project

Related

Convert below imperative java code (nested for loops) to java 8 using streams

Below is the imperative style of nested for loops. I want to make use of java 8 Streams and other features to make it a functional style.
import java.util.Arrays;
public class Java8 {
public static final String TAILS = "TAILS";
public static final String HEADS = "HEADS";
public static void main(String[] args) {
String[] coines = new String[11];
Arrays.fill(coines, TAILS);
for(int i=1;i<coines.length ; i++){
System.out.println("Person :" + i);
for (int j=1; j < coines.length ; j++){
if(j%i==0){
System.out.print("Flipping " + j +"th Element from " + coines[j] + " to ");
coines[j] = coines[j]== TAILS ? HEADS : TAILS;
System.out.println(coines[j]);
}
}
}
}
}
I think you want to do something like this
import java.util.Arrays;
import java.util.stream.IntStream;
public class Java8 {
public static final String TAILS = "TAILS";
public static final String HEADS = "HEADS";
public static void main(String[] args) {
String[] coines = new String[11];
Arrays.fill(coines, TAILS);
IntStream.range(0, coines.length).forEach(i-> {
System.out.println("Person :" + i);
IntStream.range(0, coines.length).filter(j->j%i==0)
.forEach(j -> {
System.out.print("Flipping " + j +"th Element from " + coines[j] + " to ");
coines[j] = coines[j].equalsIgnoreCase(TAILS) ? HEADS : TAILS;
System.out.println(coines[j]);
});
});
}}
Also I changed if in filter and == in equalsIgnoreCase.
One way to do it
IntStream.range(1, coins.length)
.forEach(i -> {
System.out.println("Persion :" +i);
IntStream.range(1, coins.length)
.filter(j -> j%i == 0)
.forEach(j -> {
System.out.print("Flipping " + j +"th Element from " + coins[j] + " to ");
coins[j] = coins[j].equals(TAILS) ? HEADS : TAILS;
System.out.println(coins[j]);
});
});

Reading text files into array

I'm trying to store girl and boy names into an array.
I got most of the code except the storing the files into an array.
This is what girls.txt looks like
Emma 125125
Elaina 415545
Kim 545454
Boys.txt:
Devan 45645
Tom 4545
Chris 4879797
i need help storing the names and numbers from files into array boynames array and girlnames array. I show where i need help with comments in code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1Names {
public static void main(String[] args) {
Scanner inputStream = null;
String[][] boynames = new String[1000][2];
String[][] girlnames = new String[1000][2];
String line = null;
boolean isFoundB = false;
boolean isFoundG = false;
try {
inputStream = new Scanner(new FileInputStream("boys.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file boys.txt");
System.exit(0);
}
Scanner inputStreamGirls = null;
try {
inputStreamGirls = new Scanner(new FileInputStream("girls.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file girls.txt");
System.exit(0);
}
int count = 0;
while (count < 1000){
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
count++;
}
count = 0;
while (count < 1000 ){
inputStreamGirls = girlnames[count][0]; //here
inputStreamGirls = girlnames[count][1]; //here
count++;
}
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first name that you would like to find the popularity of.\n Be sure to capitalize the first letter of the name.\n");
String answer = keyboard.next();
count = 0;
while(count < 1000){
if (boynames[count][0] == answer){
System.out.println(boynames[count][0] + " is ranked " + count + " among boys with " + boynames[count][1] + " namings");
isFoundB = true;
}
if (girlnames[count][0] == answer){
System.out.println(girlnames[count][0] + " is ranked " + count + " among girls with " + girlnames[count][1] + " namings");
isFoundG = true;
}
count++;
}
if(isFoundB == false){
System.out.println(answer + " is not ranked among the top 1000 boy names.");
}
if(isFoundG == false){
System.out.println(answer + " is not ranked among the top 1000 girl names.");
}
inputStreamGirls.close();
inputStream.close();
keyboard.close();
}
}
You will need to call the scanner methods to actually read from the input file.
scanner.next() reads one string token from the input.
So instead of this part:
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
You would do:
boynames[count][0] = inputStream.next();
boynames[count][1] = inputStream.next();

Loop, iterate with unexpected results, Propertie

package javaapplication43;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileInputStream;
public class JavaApplication43 {
int totalResults = 45; //
int itemsperPage = 10;
int i = 0;
int j = 0;
int count = 0;
FileOutputStream output = null;
Properties prop = new Properties();
FileInputStream input=null;
public JavaApplication43() throws FileNotFoundException, IOException {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("totalResults", "45");
prop.setProperty("itemsperPage", "10");
prop.setProperty("?", "?");
// save properties to project root folder
prop.store(output, null);
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("totalResults"));
System.out.println(prop.getProperty("itemsperPage"));
System.out.println(prop.getProperty("?"));
}
public void makeLoop() {
for (i = 1; i <= (totalResults / itemsperPage) + 1; i++) {
System.out.println("nextPage " + i);
for (; j < i * itemsperPage; j++) {
if (j > totalResults) {
break;
}
System.out.println("Filenumber " + (j + 1));
}
}
}
public static void main(String[] args) throws IOException {
JavaApplication43 myTest = new JavaApplication43();
myTest.makeLoop();
}
}
*This Code gives the Result:
nextPage1: Filnumber1, Filnumber2...Filenumber10
nextPage2: Filenumber11, Filenumber12.., Filenumber20
nextPage5: Filenumber41, Filenumber42.., Filenumber46
And so on. I expect the result so, if i start the next time with a sheduller it should start
with the nextpage2 and print the files from 11-20,
if i start again the programm it should start with the nextpage 3 and print the files from 21-30 and so on depends on the value wich i have for totalResults.
The Solution is may to save the value in the Property to make it Persistent, so that
if i run the Programm again, it will read the Property config.properties to start on the right index, but i dont know how to iterate, through the loop. ?
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileInputStream;
public class JavaApplication43_with_Main_3 {
public static void main(String[] args) throws IOException {
int totalResults = 45; //
int itemsperPage = 10;
int i = 0;
int j = 0;
FileOutputStream output = null;
Properties prop = new Properties();
FileInputStream input = null;
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println("nextPage Prop " + prop.getProperty("nextPage"));
String nextPage = prop.getProperty("nextPage");
int intNextPage = Integer.parseInt(nextPage);
System.out.println("intNextPage " + intNextPage);
for (i = intNextPage; i <= (totalResults / itemsperPage) + 1; i++) {
int jNextPage=intNextPage-1;
System.out.println("nextPage here " + i);
for (j=jNextPage*itemsperPage; j < i * itemsperPage; j++) {
// System.out.println("j ist "+j);
if (j > totalResults) {
break;
}
System.out.println("Filenumber " + (j + 1));
}
String strI = "" + (i + 1);
System.out.println("hello " + strI);
output = new FileOutputStream("config.properties");
prop.setProperty("nextPage", strI);
prop.store(output, null);
break;
}
}
}
This is the does make loop and printing out
nextPage 1, Filenumber1,Filenumber2,..,Filenumber10
then it saves the nextPage value into the Property File.
If you start again, it does printing out
nextPage 2, Filenumber11,Filenumber12,...,Filenumber20
You should have e Propertiy File with the Name, config.properties
and but the key nextPage and the value 1, nextPage=1;--->config.properties

outputting data from multiple methods in java

currently the program is listing the planets in a solar system. each planet entered to the solarsystem has a position counter adding position++
after all the planets are listed I want to SystemPrintln a statement saying, There are this many planets in your solar system. Should I not be able to just return position; for this?
At this point the result is in a toString so to add this final line stating the number of planets how would I do this?
Could I add a second method "position" to the toString?
can I just return position in a system.out.println statement from the drive class?
class Planet:
package planets;
public class Planet {
String name;
int moons;
public Planet(String name, int moons)
{
this.moons = moons;
this.name = name;
}
public String toString() {
return "The Planet " + name + " Has " + moons + " Moon(s) \r\n ";
}
}
Class SolarSystem:
package planets;
public class SolarSystem {
private Planet[]planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString();
}
return result;
}
}
Class Driver:
package planets;
public class Driver {
public static void main(String[]args) {
Planet mercury = new Planet ("Mercury", 0);
Planet venus = new Planet ("Venus", 0);
Planet earth = new Planet ("Earth", 1);
Planet mars = new Planet ("Mars", 2);
Planet jupiter = new Planet ("Jupiter", 67);
Planet saturn = new Planet ("Saturn", 62);
Planet uranus = new Planet ("Uranus", 27);
Planet neptune = new Planet ("Neptune", 14);
Planet pluto = new Planet ("Pluto", 5);
SolarSystem solarSystem = new SolarSystem(9);
solarSystem.add(mercury);
solarSystem.add(venus);
solarSystem.add(earth);
solarSystem.add(mars);
solarSystem.add(jupiter);
solarSystem.add(saturn);
solarSystem.add(uranus);
solarSystem.add(neptune);
solarSystem.add(pluto);
System.out.println(solarSystem);
}
}
For your class you have to return the position variabel.
public int sumPlanets(){
return position;
}
and in your method toString use :
public String toString(){
return Integer.toString(sumPlanets());
}
but i recommend only use the position for return the total elements
public String toString(){
return position;
}
In your in your code :
package planets;
public class SolarSystem {
private Planet[]planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
return Integer.toString(sumPlanets());
}
public int sumPlanets(){
return position;
}
}
In order to print out the total number of planets I used the position variable which adds one each time a planets object is made.
position++
so to print this I added
System.out.println("You Have " + position + " Planets In Your Solar System");
Directly after the loop so It would be printed out one time with the total amount.
The full class ended up like this.
package planets;
public class SolarSystem {
private Planet[]planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString();
}
System.out.println("You Have " + position + " Planets In Your Solar System");
return result;
}
}

Searching Arrays in Java: equals( ) Versus ==

I have an array with 5 elements. If a user inputs a name or a title, it should output that person's or job title's corresponding job title and person. Here's what I got, I'm not sure what I could be doing wrong. Since it's an applet, I don't need a main method right? Did I get stuff mixed up? What could I be doing wrong? Even if I input data that is stored in the array, it always gives me "input did not match any records" I would appreciate any help. Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment extends JApplet implements ActionListener
{
String[] empName = {"John Jacobs" , "Will Watts","Kevin Krust", "Allan Ayers", "Sam Smith"};
String[] empTitle = {"Software Engineer" , "Database Administrator", "Network Administrator" , "Head Programmer" ,"Department Manager"};
final int ARRAY_SIZE = 5;
boolean validName = false;
boolean validTitle = false;
String nameOfEmployee;
String titleOfEmployee;
JLabel enterInfo = new JLabel("Enter an Employee Name or Job Title");
JTextField userInput = new JTextField(20);
JButton empButton = new JButton ("Press if you entered a name");
JButton titleButton = new JButton ("Press if you entered a title");
JLabel inputDisplay = new JLabel("");
Container con = getContentPane();
public void init()
{
con.add(enterInfo);
con.add(userInput);
con.add(empButton);
con.add(titleButton);
con.setLayout(new FlowLayout());
userInput.addActionListener(this);
empButton.addActionListener(this);
titleButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source == empButton)
{
String nameEmp = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameEmp == empName[x])
{
validName = true;
titleOfEmployee = empTitle[x];
}
}
if(validName)
inputDisplay.setText(nameEmp + "is a" + titleOfEmployee);
else
inputDisplay.setText("The title you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
else
{
String nameJob = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameJob == empTitle[x])
{
validTitle = true;
nameOfEmployee = empName[x];
}
}
if(validName)
inputDisplay.setText(nameOfEmployee + "is a" + nameJob);
else
inputDisplay.setText("The name you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
con.invalidate();
con.validate();
}
}
This
nameEmp == empName[x]
compares object references. What you want is comparison of contents, so you should check
nameEmp.equals(empName[x])
When comparing the value input by the user to the values in your arrays, you need to use the equals function and not ==.
Read why here.

Resources