Print all the names inside a string array - java

I'm practicing Java and I have a question about printing all values inside a String array. I would need to print everything inside the String arrays I have created.
I can't seem to make "Arrays.toString" to work in my code and I don't want to have to point out each value inside the array. Is there a way I can print them all at once?
public class MyCode {
public static void main(String[] args) {
String[] majority = {"Congrats, you may enter!", " Awesome!"};
String[] minority = {"I'm sorry, you are too young.", " Ah that's too bad!"};
int permition = 17;
boolean authorization = (permition >= 18);
if (authorization == true) {
System.out.println(majority[0] + majority[1]);
} else {
System.out.println(minority[0] + minority[1]);
}
}
}
So, if the person is above or equal to 18, the result should be "Congrats, you may enter! Awesome!", or if below 18 "I'm sorry, you are too young. Ah that's too bad!".

You can try this
List<String>majorities =
Arrays.asList(majority);
List<String>minorities =
Arrays.asList(minority);
String str_majority = String.join("",
majorities);
String str_minority = String.join("",
minorities);
String final = str_majority +
str_minority

Related

How to put values from a text file into an object array in java?

So I am trying to create an object array that from a text file. The objects I am placing in the array are people objects with 4 parameters. 1st name, last name, an ID number and a height. The text file has a certain number of lines and each element is separated by an exclamation mark. I am trying to take each of the 4 elements to create an object and then place that object into an object array. Here is my code up until now. Also because I am new to java, there is not a lot that I know so the code needs to be simple.
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Participants {
public static void main(String[] args) {
String array[] = new String[35];
Object participants[] = new Object[35];
int count = 0;
int counter = -1;
try {
File myFile1 = new File("Participants.txt");
Scanner scan1 = new Scanner(myFile1);
while (scan1.hasNext()) {
counter++;
array[counter] = scan1.next();
}
} catch (IOException ioe) {
System.out.println("The file can not be read");
}
for (int i = 0; i < array.length; i++) {
StringTokenizer st = new StringTokenizer(array[i], "!");
while (st.hasMoreTokens()) {
People person = new People(st.nextToken(), st.nextToken(), st.nextToken(),
st.nextToken());
participants[i] = person;
}
}
}
}
I commented that your code basically looks okay. There are some problems I spotted, and I think you may be running into them. You are probably getting a
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(Unknown Source)
at java.util.StringTokenizer.<init>(Unknown Source)
at Participants.main(Participants.java:22)
because arrays[i] is empty in
StringTokenizer st = new StringTokenizer(array[i], "!");
which is because you allocate 35 entries:
String array[] = new String[35];
and the file contains less lines than that. At least, that's what I'm getting it with this input file:
A!B!C!D
E!F!G!H
I!J!K!L
which is to be expected.
If I change the first line of the input file into
A!B!C
I get
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at Text2ObjArray.main(Text2ObjArray.java:28)
which is because you only check once for a token, but then proceed to read four:
while (st.hasMoreTokens()) {
Person person = new Person(st.nextToken(), st.nextToken(), st.nextToken(), st.nextToken());
I'll update with a solution, if it is needed, but here are two suggestions:
1) use an ArrayList instead of an array[]:
2) Check what you parse: make sure there are 4 tokens per line, and deal with the exceptional case that they are not 4.
UPDATE
Basically, there's nothing wrong with your program. You already know "
How to put values from a text file into an object array in java?".
Your program runs just fine if you feed it a file with exactly 35 lines containing at least 3 exclamation marks each. If not, it throws the appropriate exceptions:
a NullPointerException if there are less than 35 lines and
an ArrayIndexOutOfBoundsException if there are more, and
a NoSuchElementException if there are less than 3 exclamation marks on any of the lines.
(Unless, there is a problem is in the People class which is unlikely if it is a POJO).
Your code only needed a few minor changes to make it work for files with other content. I've kept it simple:
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Text2ObjArray {
public static void main(String[] args) {
Person[] participants = loadFile(new File(args.length > 0
? args[0] : "Participants.txt"));
for (Person p : participants)
System.out.println("Participant: " + p);
}
I split off main merely as good practice - see 'top-down' and 'bottom-up'.
To address the NullPointerException and ArrayIndexOutOfBoundsException We'll use an ArrayList instead of an array[] to keep track of the lines we read from the file. The advantage of an ArrayList is that it can grow and shrink, which is useful if you don't know for sure if "Participants.txt" always contains 35 lines.
Also it saves us from replacing our array with a bigger one when it's full. It's a cheap, handy upgrade from an array[], and all that has changed is writing
array.get(i) instead of array[i]
array.set(i,foo) instead of array[i]=foo and
array.add(foo) instead of array[counter++]=foo and
array.size() instead of array.length. It is a dynamic array, so you can insert into any position, remove etc.
private static Person[] loadFile(File file) {
List<String> lines = new ArrayList<>();
try (Scanner scan1 = new Scanner(file)) {
while (scan1.hasNext())
lines.add(scan1.next());
} catch (IOException e) {
System.out.println("File read error: " + e.getMessage());
}
This section is changed only in that it reads up to 4 tokens, dealing with the NoSuchElementException:
Person participants[] = new Person[lines.size()];
for (int i = 0; i < lines.size(); i++) {
StringTokenizer st = new StringTokenizer(lines.get(i), "!");
String[] fields = new String[4];
for (int k = 0; k < fields.length && st.hasMoreTokens(); k++)
fields[k] = st.nextToken();
participants[i++] = new Person(fields[0], fields[1], fields[2], fields[3]);
}
return participants;
}
}
To run it successfully you'll need to replace Person to People or use this Person class:
public class Person {
private String id;
private String lName;
private String fName;
private String height;
public Person(String id, String fName, String lName, String height) {
this.id = id;
this.fName = fName;
this.lName = lName;
this.height = height;
}
public String toString() {
return "Person[" + id + ": " + lName + ", " + fName + ", " + height + "]";
}
}
I hope that this has been helpful.

How to store boolean answers in arrays and output it in Java?

I'm trying to store 5 different boolean answers (true or false) in 5 different array positions after each loop and then make a method to display the questions which were 'true'.
For example, a test run would go like this:
Question1: Content1 ~ (True or False?) False
Question2: Content2 ~ (True or False?) True
Question3: Content3 ~ (True or False?) False
(loop finished)
Question2: Content2
(exit)
And here is my code so far.
import javax.swing.*;
class booleanTest {
public static void main(String [] params) {
String[] data = {"Test1", "Test2", "Test3", "Test4", "Test5"};
boolean[] user = new boolean[5];
array_input(data, user);
System.out.println(user); // to see if it works atm
System.exit(0);
}
public static String array_input(String[] a, boolean[] b) {
String x = "";
for (int i=0; i<a.length; i++) {
x = JOptionPane.showInputDialog("Data: " + a[i]);
if(x.equals("yes")) {
b[i] = true;
}
else {
b[i] = false;
}
}
return x;
}
//public static String array_print() {
// print the boolean + question here
//}
}
It doesn't work, I understand that the b[i] = true part must be wrong, I should do something else?
If the value at an index of the boolean array is true, print out the value in the String array at that index.
public static void printTrue(boolean[] answers, String[] questions) {
// checking both indices to avoid ArrayIndexOutOfBoundsException
for (int i = 0; i < answers.length && i < questions.length; i++) {
// if the answer is true
if (answers[i]) {
System.out.println(questions[i] + ": " + true);
}
}
}
When you say System.out.println(user); prints something like [Z#3b9187c7, this is because the toString() implementation for Object returns class name + # + hex hashCode().
The Arrays#toString method creates a more readable result:
[false, false, false, true, true]
You only have to return values in a method when you have no other way of accessing the data. If you look at your code you see that you're not even using the returned value, and the last values for x will never be useful anyway. In that kind of case, you can make it a void method. Void methods are used when you want it to perform some kind of operation, but don't need it to return any values. Your code works because an array is an Object and the changes done to it can be seen even outside the method.
Here's more or less how I would implement it. Notice the variable names are a little more descriptive.
import javax.swing.*;
public class Main {
public static void main(String[] args) {
String[] questions = {"Test1", "Test2", "Test3", "Test4", "Test5"};
boolean[] responses = getUserResponses(questions);
}
public static boolean[] getUserResponses(String[] questions) {
boolean[] responses = new boolean[questions.length]; //use the length of the other array. Don't count on it always being 5
for (int i = 0; i< questions.length; i++) {
String x = JOptionPane.showInputDialog("Data: " + questions[i]);
if(x.equals("yes")) {
responses[i] = true;
}
else {
responses[i] = false;
}
}
return responses;
}
}
In general, it's better not to modify parameter Objects and to instead return new ones. Sometimes it is much more useful or necessary to do it that way, but in your case it was not.
It looks like you're on the correct path.
Array creation and element assignment:
Your code for this looks fine. You create the array using the new operator, as you would any object, but must specify an array size, as you did. Element assignment is done using an index, either an integer literal or an integer variable (in the case of your code above). Array indices range from 0 to size-1. It looks like you also got that part right.
Printing the results:
In your scenario, you only want to some of the results, where the array value is true. A simple loop with an if(user[i]) would do the trick.
for (int i = 0; i < user.length; i++) {
if (user[i]) {
System.out.println(data[i] + " = " + true);
}
}

Java - static constructor

Hey there Stackoverflowers,
I just started programming in Java and encountered a strange problem concerning printing an object. When a new object of type gast is created the user has to enter his or her birthday. This al works fine, however, if I try to print it out I returns 0-0-0. Why is that? By the way, if I create a new datum directly with the parameter constructor it works fine. Wherein lays the problem? I just can't figure it out. I hope you guys can help me out.
Thanks in advance!
public class Datum {
private static String patroon = "\\d{2}-\\d{2}-\\d{4}";
public int dag;
public int maand;
public int jaar;
Datum(int dag, int maand, int jaar) {
System.out.print("constructor: " + dag);
this.dag = dag;
System.out.println(", dag: " + this.dag);
this.maand = maand;
this.jaar = jaar;
}
Datum() {
newDatum();
}
/* */
public static Datum newDatum() {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
Datum datum = new Datum(dag, maand, jaar);
System.out.println(datum);
return datum;
}
else {
return new Datum();
}
}
public String toString() {
return this.dag + "-" + this.maand + "-" + this.jaar;
}
}
Second class:
Gast() {
this.firstName = Opgave5.userInput("Voornaam gast");
this.lastName = Opgave5.userInput("Achternaam gast");
this.geboortedatum = new Datum();
System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0
}
public String toString() {
return this.firstName + " " + this.lastName + " " + this.geboortedatum;
}
I think you don't understand constructors in Java. You are merely ignoring the result of newDatum() in the constructor. Also, if it did have the expected effect, it might recurse infinitely in the constructor invocation inside newDatum(). Use something like this; allowing newDatum() to edit the instance will work:
Datum() {
newDatum(this);
}
public static void newDatum(Datum instance) {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
instance.dag = dag;
instance.maand = maand;
instance.jaar = jaar;
System.out.println(instance);
}
else {
new Datum();
}
// ^^ Above code may be buggy, see my answer above code
}
This line:
this.geboortedatum = new Datum();
Is using the default constructor. This will set no values. Try to pass the parameters in via constructor like this:
this.geboortedatum = new Datum(1, 2, 3);
If you want to take advantage of the static method you wrote (which is where you ask for user input), then do the following:
this.geboortedatum = Datum.newDatum();

Constantly getting NullPointerException

I am making a program in which it encrypts words into some kind of secret message, but I keep on getting an error. Yes, I know the code is ugly... but I am a beginner.
Here is my main.
public class Main {
public static void main (String args []){
String message;
message = JOptionPane.showInputDialog("Give me something to crypt!");
Crypt secret = new Crypt();
secret.CyptedMessage(message);
}
}
Here is my class.
public class Crypt {
String letter[];
String message;
public Crypt(){
message = "";
letter[0]="A";
letter[1]="B";
letter[2]="C";
letter[3]="D";
letter[4]="E";
letter[5]="F";
letter[6]="G";
letter[7]="H";
letter[8]="I";
letter[9]="J";
letter[10]="K";
letter[11]="L";
letter[12]="M";
letter[13]="N";
letter[14]="O";
letter[15]="P";
letter[16]="Q";
letter[17]="R";
letter[18]="S";
letter[19]="T";
letter[20]="U";
letter[21]="V";
letter[22]="W";
letter[23]="X";
letter[24]="Y";
letter[25]="Z";
letter[26]=" ";
}
int getRandomCrypt(){
//Random number 1 to 25
int x;
x=(int)(1 + Math.random()*25);
return x;
}
int checkLetter(String subMessage){
//Checks letters
boolean b = false;
int i=0;
while (b = false){
if (i == 27){
i=0;
if (subMessage == letter[i])
return i;
else
i++;
}
}
return 0;
}
void CyptedMessage(String message){
String CyptedMessage = null;
String message1;
for (int i = 0; i < message.length(); i++){
int number = checkLetter(message.substring(i, i+1));
message1 = letter[number + getRandomCrypt()];
if (number + getRandomCrypt()>26){
message1 = letter[i-27];
}
CyptedMessage += message1;
}
System.out.print(CyptedMessage);
}
}
When I run this I get...
Exception in thread "main" java.lang.NullPointerException
at Crypt.<init>(Crypt.java:9)
at Main.main(Main.java:9)
As Serge pointed out, String letter[] is an array declaration, not an initialization. You need to then initialize it to define an exact size.
public Crypt(){
letter = new String[27]; //define array
message = "";
letter[0]="A";
letter[1]="B";
letter[2]="C";
letter[3]="D";
letter[4]="E";
letter[5]="F";
letter[6]="G";
letter[7]="H";
letter[8]="I";
letter[9]="J";
letter[10]="K";
letter[11]="L";
letter[12]="M";
letter[13]="N";
letter[14]="O";
letter[15]="P";
letter[16]="Q";
letter[17]="R";
letter[18]="S";
letter[19]="T";
letter[20]="U";
letter[21]="V";
letter[22]="W";
letter[23]="X";
letter[24]="Y";
letter[25]="Z";
letter[26]=" ";
}
Edit: forgot ;
And others beat me :P
You are not initializing your String letter[]; and directly adding values into it
do this in your constructor
letter = new String[size];
or do this in starting String letter[] = new String[size];
and in your case size is 27
You need to initialize you array ans not just define it.
String letter[] = new String[27];
Also you can put a NPE check before using the array data
if(letter[number + getRandomCrypt()] != null)
message1 = letter[number + getRandomCrypt()];
Your String letter[]; is not instantiated.
add letter = new String[size]; in your Constructor of Crypt before initialization.
In class Crypt, you declare a string array named letters, but you do not initialize it when you use it. That is why you encounter a NullPointerException.
Initilize it before you use it.
public Crypt(){
**letter= new String[27];**
letter[0]="A";
letter[1]="B";
... ...
}

getting duplicate array output - java

Can someone could be kind and help me out here. Thanks in advance...
My code below outputs the string as duplicates. I don't want to use Sets or ArrayList. I am using java.util.Random. I am trying to write a code that checks if string has already been randomly outputted and if it does, then it won't display. Where I am going wrong and how do I fix this.
public class Worldcountries
{
private static Random nums = new Random();
private static String[] countries =
{
"America", "Candada", "Chile", "Argentina"
};
public static int Dice()
{
return (generator.nums.nextInt(6) + 1);
}
public String randomCounties()
{
String aTemp = " ";
int numOfTimes = Dice();
int dup = 0;
for(int i=0 ; i<numOfTimes; i++)
{
// I think it's in the if statement where I am going wrong.
if (!countries[i].equals(countries[i]))
{
i = i + 1;
}
else
{
dup--;
}
// and maybe here
aTemp = aTemp + countries[nums.nextInt(countries.length)];
aTemp = aTemp + ",";
}
return aTemp;
}
}
So the output I am getting (randomly) is, "America, America, Chile" when it should be "America, Chile".
When do you expect this to be false?
countries[i].equals(countries[i])
Edit:
Here's a skeleton solution. I'll leave filling in the helper methods to you.
public String[] countries;
public boolean contains(String[] arr, String value) {
//return true if value is already in arr, false otherwise
}
public String chooseRandomCountry() {
//chooses a random country from countries
}
//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
while (true) {
String randomCountry = chooseRandomCountry();
if ( !contains(selection, randomCountry ) {
selection[i] = randomCountry;
break;
}
}
}
//...then build the string here
This doesn't check important things like the number of unique countries.
You need a data structure which allows you to answer the question "does it already contain item X?"
Try the collection API, for example. In your case, a good candidate is either HashSet() or LinkedHashSet() (the latter preserves the insert order).
You'd probably be better of using another structure where you save the strings you have printed. Since you don't want to use a set you could use an array instead. Something like
/*
...
*/
bool[] printed = new bool[countries.length];
for(int i=0 ; i<numOfTimes ; /*noop*/ )
{
int r = nums.nextInt(countries.length);
if (printed[r] == false)
{
i = i + 1;
printed[r] = true;
aTemp = aTemp + countries[r];
aTemp = aTemp + ",";
}
}
return aTemp;
Consider what you're comparing it to:
if (!countries[i].equals(countries[i]))
are you comparing c[i] to c[i]? or c[i] to c[i-1]? Or do you need to check the whole array for a particular string? Perhaps you need a list of countries that get output.
make list uniqueCountries
for each string called country in countries
if country is not in uniqueCountries
add country to uniqueCountries
print each country in uniqueCountries
When you do this, watch out for index out of bounds, and adjust accordingly
Much faster way to do it then using HashSets and other creepy stuff. Takes less code too:
public String randomCounties() {
List<String> results = Arrays.asList(countries);
Collections.shuffle(results);
int numOfTimes = Dice();
String result = " ";
for(int i=0 ; i<numOfTimes; i++) {
result = result + countries[i] + ", ";
}
return result;
}
If you want to avoid outputting duplicate values, you need to record what values have already been listed or remove values from the pool of possibilities when they get selected.
You mention that you do not want to use Sets or ArrayList (I assume you mean Lists in general), I assume that is a requirement of the assignment. If so, you can accomplish this by building arrays and copying data between them the same way that an ArrayList would.
one note, your current implementation chooses between 1 and 6 entries from and array of 4 entries. If you force the selections to be unique you need to decide how to handle the case when you have no more unique selections.

Categories

Resources