Array only printing final element JAVA? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
private static String[] nameArray;
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
name = scanner.nextLine();
nameArray = new String[] {
name
};
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for (String something: nameArray) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}
Hello all thanks in advance for your help I m having a problem I have a loop that call a method once a number is entered in that method is this:
So my question whenever I call the newPerson method and enter a name instead of having all the names stored and in the array and later printed, the personInfo method only prints the final name that I enter in the array why is it not displaying all the names?

You're replacing the nameArray entirely after each input. You have to add it to your array. But it is easier to use 'ArrayList's in this case.
Building on your provided code:
private static ArrayList<String> nameArray = new ArrayList<>();
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
name = scanner.nextLine();
nameArray.add(name);
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for ( String something : nameArray) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}

every time you are creating new string array with one element
nameArray = new String[]{name};
so the latest one will be preserved which is your last element. So make sure that you are appending your names to nameArray.

Better to use ArrayList if you are not sure the eventual size of the array.
private static List<String> nameList = new ArrayList<String>();
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
nameList.add(scanner.nextLine());
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for (String something: nameList) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}
You can still do it using array but you have to do lot of work during adding new element into array, probably you will need maintain the index for next insertion, provide initial size of array and in case it overflows then resize the array.

When you do
nameArray = new String[]{name};
you are overriding the contents of nameArray, thus losing all previously saved names. new String[]{name} creates a new String array.
Use a list of String instead of an array and just add the new names to it.
// use List<String> instead of String[]
private static List<String> names = new ArrayList<String>();
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
name = scanner.nextLine();
// add new names to list, old names will not be deleted
names.add(name);
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for(String something : names) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}

You are creating and replacing an existing every time you take input from user . Replace that add input in a list .

Related

How to edit the contents of an ArrayList in-place while looping [duplicate]

This question already has answers here:
How to change value of ArrayList element in java
(7 answers)
Closed 6 years ago.
Assume I have an ArrayList of Strings that holds the words, "hello" and "world". I want to add the word "java" to the end of each.
I have tried to do it while looping, but did not succeed. Please suggest me a method for the same.
The other way, I found was to create a different ArrayList and copy contents, however I don't think is efficient in terms of space.
import java.util.ArrayList;
public class EditArrayListInLoop {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello");
arrayList.add("world");
/* This does not work */
/*for(int i = 0;i<arrayList.size();i++)
{
arrayList.get(i) += "java";
}*/
ArrayList<String> arrayList2 = new ArrayList<String>();
for(int i = 0;i<arrayList.size();i++)
{
String test = arrayList.get(i);
test += "java";
arrayList2.add(test);
}
System.out.println(arrayList2);
}
}
test += "java"; doesn't change the content of the String returned by arrayList.get(i). It creates a new String. Strings are immutable, so there isn't any way to change the String objects within the List. You can only replace them by new String objects.
Use arrayList.set(index,newValue) to replace the i'th element of the List:
for(int i = 0;i<arrayList.size();i++)
{
arrayList.set(i,arrayList.get(i)+"java");
}
I think you should manipulate the first list only. Using an another list is not an optimal solution.
Here's the code.
Output
[hellojava, worldjava]
Code
import java.util.ArrayList;
public class EditArrayListInLoop {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello");
arrayList.add("world");
for(int i = 0;i<arrayList.size();i++)
arrayList.set(i, arrayList.get(i).concat("java"));
System.out.println(arrayList);
}
}
Please note that Strings are immutable. Whenever you change the content of String, you're not actually appending anything behind the scenes. You are creating a completely new String.
If the contents of your Strings are expected to change, then the advisable way is to use the StringBuilder class instead:
Documentation
The principal operations on a StringBuilder are the append and insert
methods, which are overloaded so as to accept data of any type. Each
effectively converts a given datum to a string and then appends or
inserts the characters of that string to the string builder. The
append method always adds these characters at the end of the builder;
the insert method adds the characters at a specified point.
Here's the code:
import java.util.ArrayList;
public class EditArrayListInLoop {
public static void main(String[] args) {
ArrayList<StringBuilder> arrayList = new ArrayList<StringBuilder>();
arrayList.add(new StringBuilder("hello"));
arrayList.add(new StringBuilder("world"));
for(int i = 0;i<arrayList.size();i++)
arrayList.set(i, arrayList.get(i).append("java"));
System.out.println(arrayList);
}
}
P.S.: If such synchronization is required then it is recommended that StringBuffer be used.
try using the set method.
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello");
arrayList.add("world");
for(int i = 0;i<arrayList.size();i++)
{
String str = arrayList.get(i);
arrayList.set(i, str + " java");
}
for(int i = 0;i<arrayList.size();i++)
{
String str = arrayList.get(i);
System.out.println(str);
}
You are looking for:
arrayList.set(i, arrayList.get(i) + "java");
More info on ArrayList: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

How to create new object in a for loop?

I want to create some objects in a program using for loop. The parameters of the objects are accepted from key board. My question is how to create different objects in a for loop. Here is what I have.
import java.io.*;
import java.util.*;
public class TimeToGraduate {
public static void main(String[] args){
class Course{
Course (String name, String sem, int numOfPre){
this.name = name;
this.sem = sem;
this.numOfPre = numOfPre;
}
String name;
String sem;
int numOfPre;
}
Scanner scanner = new Scanner(System.in);
System.out.print("Input two integers here: ");
String totalCourse = scanner.nextLine();
String[] numOfCourse = totalCourse.split(" ");//[0] num of total course [1] max num per semester
for(int i = 0;i < Integer.parseInt(numOfCourse[0]); i++){
System.out.print("Please input course info here: ");
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
String courseName = infoOfCourse[0];
String courseSem = infoOfCourse[1];
int courseNumOfPre = Integer.parseInt(infoOfCourse[2]);
Course course = new Course(courseName,courseSem,courseNumOfPre);
//How to create different objects?
}
scanner.close();
}
}
You could save the objects you are creating in an array.
Before the for loop:
// create an empty array with the size of the total courses
int numOfCourses = Integer.parseInt(numOfCourse[0]);
Course courses[] = new Course[numOfCourses];
Inside the loop:
courses[i] = new Course(courseName, courseSem, courseNumOfPre);
Collection
The answer by Securo is correct. But rather than an array, it is more flexible and powerful to use a Collection. If you want to keep the objects in the order of their creation, use the List interface, with an ArrayList as the implementation.
Before the loop starts, define an empty List.
List<Course> courses = new ArrayList<>();
If you know the number of courses, pass that number as the initial size of the ArrayList. Helps performance and memory usage a little bit if the ArrayList need not be resized.
List<Course> courses = new ArrayList<>( numberOfCourses );
In your loop, instantiate the objects and add to the List.
Course course = new Course( … );
courses.add( course );

Array Lists, reading in from file and 2 Classes

I'm learning arraylists, I'm unsure of how to read in from file and add it to a list as I am much more used to arrays, are they alike?
I'm also getting many errors when I am trying to instantiate the class object 'film' but never mind about it.
How am I able to get load my file method working? To me it looks right I think I just need a strangers pov.
Also getting an error when trying to find the file symbol. If there is any specific readings I should do for array lists could you please link me or explain best you can.
I'm very new to both coding and stack overflow so if you could dumb anything down and please be patient if I don't understand anything thanks.
import java.util.*;
public class CinemaDriver {
film[] Film;
public static void main(String[] args) {
Film = new film[100];
ArrayList <Film> list = new ArrayList<Film> ();
}
public void readFromFile() {
File f = new file("file.txt");
Scanner infile = new Scanner(f);
int x = infile.nextInt();
for(int i = 0; i < x ; i++) {
String title = infile.nextLine();
String genre = infile.nextLine();
int screenings = infile.nextInt();
int attendance = infile.nextInt();
file.nextLine();
list.add(title,genre,screenings,name);
}
infile.close();
}
public void displayAll() {
for (film f : list ){
System.out.println(f +"/ \n");
}
}
}
Your ArrayList keeps Film objects as defined here:
ArrayList <Film> list = new ArrayList<Film> ();
But you are trying to insert several different objects or values (Strings, ints, etc...) instead of a Film object
list.add(title,genre,screenings,name);
What you should do is something like this:
Option 1:
list.add(new Film(title,genre,screenings,name));
Option2:
Film f = new Film();
f.setTitle(title);
f.setGenre(genre);
f.setScreenings(screenings);
f.setName(name);
list.add(f);

Java split and add elements into corrsponding data type arraylists

My problem is when a user enters text it should have two elements to split when using .split() however with the items it splits how do I put them into different lists so that I can use integer based list to make calculations.
e.g.
a user enters "skyrim , 100" the 'skyrim' entry is a string however with the number (integer) '100' I want to split it removing the comma and add it to a ArrayList for calculations and with other inputs added.
game name(String) , hours(integers) <- template
skyrim , 100
oblivion , 25
GTA V , 50
so the listed items above are user input with 2 arguments separated by a comma, which will be split, then I need to add them to different arraylists.
Scanner input = new Scanner(System.in);
Arraylist<String> game = new Arraylist<>();
Arraylist<Integer> hours = new Arraylist<>();
Arraylist<Object> allGameData = new Arraylist<>();
String gameEntry = input.nextLine().split(" , ");
allGameData.add(gameEntry);
foreach(object items : allGameData) {
System.out.println(items);
}
so from here I should have:
skyrim , 100 , oblivion, 25, GTAV , 50
How do i put the game names into the game list and the numbers into the hours list?
Well for starters, the class you should be using is ArrayList with a capital L. So you need to change:
Arraylist<String> game = new Arraylist<>();
Arraylist<Integer> hours = new Arraylist<>();
Arraylist<Object> allGameData = new Arraylist<>();
to this:
ArrayList<String> game = new ArrayList<>();
ArrayList<Integer> hours = new ArrayList<>();
ArrayList<Object> allGameData = new ArrayList<>();
After we have them initialized correctly we add to the ArrayList with #.add so in your case you would add to the game and hours list like:
game.add("some game");
hours.add(10);
When you split your input with input.nextLine().split(" , "); we are expecting a String array to be returned. Currently you are trying to set this to just a String instead of a String array.
while (true){
System.out.println("Enter \"game , hours\" or \"Quit\"");
String line = input.nextLine();
if (line.equals("Quit")) break;
allGameData.add(line);
String[] parsedData = line.split(" , ");
game.add(parsedData[0]);
hours.add(Integer.parseInt(parsedData[1]));
}
You can use Integer.parseInt(). The code you submitted looks pseudo-codey, but this is something like what You're going for:
String gameEntry = input.nextLine();
allGameData.add(gameEntry);
String[] splitGameEntry = input.nextLine().split(" , ");
game.add(splitGameEntry[0]);
hours.add(Integer.parseInt(splitGameEntry[1]));
I don't know exactly what you're trying to accomplish with this code, but you may want to organize the game/hours into a class that holds both values. Your code would then look something like this:
public class GameInfo
{
private String name;
private int hours;
public GameInfo(String name, int hours)
{
this.name = name;
this.hours = hours;
}
[getters/setters]
#Override
public String toString()
{
return name + ": " + hours + " hours played!";
}
}
public class Main
{
public void doSomething()
{
Scanner input = new Scanner(System.in);
List<GameInfo> gameInfo = new ArrayList<>();
String[] gameEntry = input.nextLint().split(" , ");
gameInfo.add(new GameInfo(gameEntry[0], Integer.parseInt(gameEntry[1]));
for(GameInfo gameInfoPiece : gameInfo)
{
System.out.println(gameInfoPiece);
}
}
}
Using this approach, you would be able to add as much information into the GameInfo class as you want. For instance, if you wanted to change hours to expectedHoursToComplete and add actualHoursToComplete, you could easily do that.
You may find it easier if you rethink your approach. Rather than have 3 separate lists why not store it all in a single Map<String,Integer> where the key is the game name and the value is the number of hours.
Your code would look something like the following:
Scanner scan = new Scanner(System.in);
Map<String, Integer> gameHoursMap = new HashMap<>();
String currentValue = scan.nextLine();
// Loop until you meet some criteria to end such as typing q or quit
while(!currentValue.equalsIgnoreCase("q")){
// You would need to handle when the value of currentValue doesn't fit what you would normally be expecting before doing the rest
String[] vals = currentValue.split(",");
// Call trim method on the String incase there is any lingering whitespace
gameHoursMap.put(vals[0].trim(), Integer.valueOf(vals[1].trim()));
currentValue = scan.nextLine();
}
You would obviously need to write some error handling for when the input doesn't fit with what you're expecting but you get the gist.
UPDATE:
If you wanted to have more complicated info stored for each game you could wrap it up in a custom class GameInfo and then have a Map<String,GameInfo> where the key is the name and the value is the GameInfo. This would allow you to retrieve all of the game info for a game just based on the name.
public class GameInfo {
private String name;
private int hoursPlayed;
private int level;
// etc
}
You would then amend the while loop to create the GameInfo object instead of just putting a String and int into the Map
// Create the GameInfo object from the corresponding input supplied by the user
GameInfo game = new GameInfo(vals[0].trim(), Integer.valueOf(vals[1].trim()), Integer.valueOf(vals[2].trim()));
// Put it in the map with the name as the key
gameMap.put(game.getName(), game);

Hashtag Multiple

I am trying to find the number of unique hashtags in a tweet inputted by a user. for example, if someone inputs "#one #seven #one purple green #red", it would show 3 unique hashtags that would be "#one, #seven, #red". In my code, I can do that to one tweet, but I cannot figure out how to input multiple tweets and find all the unique hashtags from them.
package edu.bsu.cs121.jmgibson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Tweet {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a tweet");
String tweet = scanner.nextLine();
Set<String> hashtags = getHashtags(tweet);
System.out.println(hashtags.toString());
}
public static Set<String> getHashtags(String tweet) {
String[] words = tweet.split(" ");
Set<String> hashtags = new HashSet<String>();
for (String word : words) {
if (word.startsWith("#")) {
hashtags.add(word);
}
}
return hashtags;
}
}
I don't want to do your homework for you, but I'll offer some suggestions:
In main(), you'll need a loop that asks for input and makes calls
to getHashtags().
Instead of creating a new HashSet inside of getHashtags(),
create one in main() (outside of the loop), and pass it in.
1.loop and get many tweet inputs
something like
for(int i=0;i<100;i++)
{
System.out.println("Please enter a tweet");
String tweet[i] = scanner.nextLine();
}
2.pass the tweetstring array instead of passing tweet string
3.loop through tweet array line by line and add tag if and only if not already added
public static Set<String> getHashtags(String[] tweet) {
Set<String> hashtags = new HashSet<String>();
//loop of tweet array starts
String[] words = tweet[i].split(" ");//i is loop variable
for (String word : words) {
if (word.startsWith("#")) {
//here add condition to check if hashings already doesnt have the word
hashtags.add(word);
}
}
}
//loop ends
return hashtags;
You need a loop in your main to gather multiple inputs.
I would gather your inputs into one string in order to work with your already defined getHashtags.
Something like this...
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a tweet");
String tweet = "";
while(!scanner.nextLine().equals("stop")){
tweet += scanner.nextLine();
}
Set<String> hashtags = getHashtags(tweet);
System.out.println(hashtags.toString());
}
So a loop and a += should do the trick.

Categories