Putting user created variables inside of an array - java

I want to put what the use puts in for x to be stored in the yourNumbers array, how would I do that? Edit: How would I clean up the println parts at the bottom, using loops.
import java.util.Scanner;
public class array {
public class SS_Un8As1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] yourNumbers = new int[10];
for (int counter=0; counter < yourNumbers.length; counter++){
System.out.print("Enter your number: ");
yourNumbers[counter] = scan.nextInt();
}
System.out.println("Original numbers: " + yourNumbers[0] + "," + yourNumbers[1] + "," + yourNumbers[2] + "," + yourNumbers[3] + "," + yourNumbers[4] + "," + yourNumbers[5] + "," + yourNumbers[6] + "," + yourNumbers[7] + "," + yourNumbers[8] + "," + yourNumbers[9]);
System.out.println("Original numbers multiplied by five: " + yourNumbers[0]*5 + "," + yourNumbers[1]*5 + "," + yourNumbers[2]*5 + "," + yourNumbers[3]*5 + "," + yourNumbers[4]*5 + "," + yourNumbers[5]*5 + "," + yourNumbers[6]*5 + "," + yourNumbers[7]*5 + "," + yourNumbers[8]*5 + "," + yourNumbers[9]*5);
System.out.println("Original numbers minus the next number: " + (yourNumbers[0]-yourNumbers[1]) + "," + (yourNumbers[1]-yourNumbers[2]) + "," + (yourNumbers[2]-yourNumbers[3]) + "," + (yourNumbers[3]-yourNumbers[4]) + "," + (yourNumbers[4]-yourNumbers[5]) + "," + (yourNumbers[5]-yourNumbers[6]) + "," + (yourNumbers[6]-yourNumbers[7]) + "," + (yourNumbers[7]-yourNumbers[8]) + "," + (yourNumbers[8]-yourNumbers[9]) + "," + (yourNumbers[9]-yourNumbers[0]));
}
}

Like this:
yourNumbers[counter] = x;
The above code is stating: store the value of x in the array yourNumbers in the index (position) counter. Because counter is the iteration variable of a for loop, each time the loop advances the counter the next value of x will be stored in the next available position in the array.
You must make sure that the length of the array is the same as the value of counter. In your code, do this:
int[] yourNumbers = new int[10];
Why? because counter goes from 0 to 9, so the array must be of length 10.

replace this
int x = scan.nextInt();
with
yourNumbers[counter] = scan.nextInt();
also, the condition should be counter<9, or better counter<yourNumbers.length

Simply pass the input into the next element of the array, while inside the for loop:
yourNumbers[counter] = x;
I should also point out, however, that you should validate that your input is actually an integer before assigning x the value. If the value isn't an integer, your program will crash.

Related

Displaying number of times a character is in a string

I need to print the amount of times an input character appears in the string. It runs and works for all tests, however when a character appears only 1 time it prints "1 times" instead of "1 time" like expected, and i am unsure of how to add this into my code. It has to be when count is equal to 1 the outprint changes from times to time. I am lost.
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
Expected to
You should add a condition for the same instead of printing the static string "times" as below:
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
String str = (count==1)?"time":"times";
System.out.println("The letter '" + letter + "' appears " + count + str + " in the string " + "\"" + input + ".\"");
Maybe try something like this
String plural = (count == 1) ? "" : "s";
System.out.println("The letter '" + letter + "' appears " + count + " time" + plural + "in the string " + "\"" + input + ".\"");
I would use an if statement to determine how many times this specific letter appears in your string. Also, since first character is charAt(0), the last character should be charAt(s.length()-1);.
for( i = 0; i < (input.length()-1); i ++){
if (input.charAt(i) == letter)
count = count + 1;
} //end of your for loop
if (count == 1){
System.out.println("The letter '" + letter +
"' appears " + count + " time in the string " + "\"" + input + ".\"");
}
else{
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
}

CSVWriter only writes last line in Java

I'm trying to get the print output and store it into an array of Strings in order to write the values in a CSV File. The problem that comes up is that when a run the code, from 100 lines printed, only the last line gets stored:
public void organize(String line) throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter("out.csv"), '\t');
String[] token = line.split(",");
String[] DependencyItems = token[1].split(" ");
List<String> entriesList;
String[] entries;
String row = "";
for (int i = 0; i < DependencyItems.length; i++) {
row = token[0] + "," + DependencyItems[i] + "," + token[2] + "," + token[3] + "," + token[5]+ "," + token[6]
+ "," + token[7]+ "," + token[8]+ "," + token[9] + "," + token[10] + "," + token[11] + "," + token[12]
+ "," + token[13] + "," + token[14] + "," + token[15] + "," + token[16]+ "," + token[17]
+ "," + token[18]+ "," + token[19]+ "," + token[20]+ "," + token[21] + "," + token[22]
+ "," + token[23]+ "," + token[24]+ "," + token[25]+ "," + token[26]+ "," + token[27]
+ "," + token[28]+ "," + token[29];
}
System.out.println(row);
entriesList = Arrays.asList(row);
entries = entriesList.toArray(new String[0]);
writer.writeNext(entries);
writer.close();
}
What I am doing wrong?
row = <big long string>
You are always resetting row then all of the stuff after the loop is just using the last value of row. If you want to use all the values, perhaps the code after the loop should be in the loop? At the very least it looks like these 2 lines belong in the loop.
System.out.println(row);
entriesList = Arrays.asList(row);
Note that if the scope of row was limited to just be inside the loop, then this may help to identify this type of issue as it would not be valid outside the loop.

how to find a letter in a string and how to return two strings in alphabetical order? java [duplicate]

This question already has answers here:
Comparing strings by their alphabetical order
(10 answers)
Closed 8 years ago.
How can I print which word comes first (alphabetically) when I prompts the user to write two words? and how to check if a certain character exist in that scanned words?
For ex: if the user wrote "Word" and "Apple" how can I print these two words in alphabetical order. Also, I wrote a program to check if char 'z' appears on either words or not, but I don't know what's wrong about it? Here is my program:
import java.util.*;
public class Pr7{
public static void main(String[] args){
//print two words and read them..
Scanner scan = new Scanner (System.in);
String Word1;
String Word2;
System.out.println();
System.out.print("* Please write one word: ");
Word1 = scan.nextLine();
System.out.print("* Please write one word: ");
Word2 = scan.nextLine();
//Prints which word has more characters in it..
if (Word1.length() > Word2.length())
System.out.println("- " + "(" + Word1 + ")" + " has more characters.");
else if (Word2.length() > Word1.length())
System.out.println("- " + "(" + Word2 + ")" + " has more characters.");
else
System.out.println("- " + "(" + Word1 + ")" + " has equal characters with " + "(" + Word2 + ")");
//Prints which word comes first (alphabetically)..
/*
char ch;
int compare = Word1.compareTO(Word2);
*/
//Prints whether the letter 'z' appears in either word..
if (Word1.indexOf('z') == true)
System.out.print("- Letter 'z' appears in the first word.");
else if (Word2.indexOf('z') == )
System.out.print("- Letter 'z' appears in the second word.");
else
System.out.print("- Letter 'z' doesn't appears in either word.");
System.out.println();
//Prompts the user for a sentence and reads it..
String Str1;
String Str2;
System.out.println();
System.out.print("* Please write a string: ");
Str1 = scan.nextLine();
System.out.print("* Please write a string: ");
Str2 = scan.nextLine();
//Prints how many characters are in the first sentence and the second sentence..
if (Str1.length() > Str2.length()){
System.out.println("- " + "(" + Str1 + ")" + " has more characters.");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
else if (Str2.length() > Str1.length()){
System.out.println("- " + "(" + Str2 + ")" + " has more characters.");
System.out.print("- " + "(" + Str2 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word1 + ")" + " = " + Word1.length() + " Character(s)");
}
else{
System.out.println("- " + "(" + Str1 + ")" + " has equal characters with " + "(" + Str2 + ")");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str1.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
System.out.println();
}//main
}//Pr7
I know the methods I need to call, but I don't know how to use it.
To sort a list of strings in alphabetical order, you can do the following:
List<String> lst = new ArrayList<>();
lst.add("asd");
lst.add("ffsd");
Collections.sort(lst, new Comparator<String>() {
#Override
public int compare(String foo, String bar) {
return String.CASE_INSENSITIVE_ORDER.compare(foo, bar);
}
});
// will print the first of the sorted strings
System.out.println(lst.get(0));

Infinitely Looping if statement

First: I keep running into an infinite loop in the following code. The code is built so that you enter 8 numbers between 1 and 10. It proofs that these numbers are between 1 and 10. Then the second proof is that these 8 numbers added together equal 60. I'm having trouble with the end if else statement. If the total of the numbers is 60 it works fine and gives the print out but if it gets stopped at the if statement it infinitely prints the "You've entered the wrong total number" printout as well as an ever increasing total number of points. Am I missing something easy like a parenthesis or something?
Secondly: How can I loop back to the original entering of values if the total is not 60 and start the whole process over?
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
while (jamesTotalQuarter != 60){
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
}
}
}
Let me know if the following code solves your problem. Have not tested it, but it should just work fine now. Get the logic and fix it yourself incase of errors.
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
While(true){ // keeps it in a loop forever and only a "break" statement can stop it
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
continue; // loop execution starts from the beginning and your program gets fresh inputs.
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
break; // breaks from the loop on correct input
}
}
}

difficulty in List iteration and comparison in java

I have 2 list List<String> existingGuesses which contains characters and List<String> word = new ArrayList<String>(words) which contains words which is a copy of list words as shown in my code below. What I am trying to do is to iterate through all the words of List word and iterate through the characters of list existingGuesses. Then I want to compare the first character of List existingGuesses with all the words of List word one by one and if a match is found then I want to remove the word from the list. Then the same for next character and continue until there are no more words left to compare. Until now, I could only declare a iterator, it's not necessary to use iterator but I don't know any other ways. My code is as follows:
public List<String> getWordOptions(List<String> existingGuesses, String newGuess)
{
List<String> word = new ArrayList<String>(words);
String c = existingGuesses.get(0); //trying to get the first character
ListIterator<String> iterator = word.listIterator(); //iterator to iterate thorugh word list
while(iterator.hasNext())
{
if(word.contains(c)) //trying to compare
{
word.remove(c);
}
}
return null;
}
Can anybody help me out? The original List words is:
private List<String> words = new ArrayList<String>() {
{
// DO NOT CHANGE THESE WORDS!
String w =
"sentence\n"
+ "together\n"
+ "children\n"
+ "mountain\n"
+ "chipmunk\n"
+ "crashing\n"
+ "drinking\n"
+ "insisted\n"
+ "insulted\n"
+ "invented\n"
+ "squinted\n"
+ "standing\n"
+ "swishing\n"
+ "talented\n"
+ "whiplash\n"
+ "complain\n"
+ "granddad\n"
+ "sprinkle\n"
+ "surprise\n"
+ "umbrella\n"
+ "anything\n"
+ "anywhere\n"
+ "baseball\n"
+ "birthday\n"
+ "bluebird\n"
+ "cheerful\n"
+ "colorful\n"
+ "daylight\n"
+ "doghouse\n"
+ "driveway\n"
+ "everyone\n"
+ "faithful\n"
+ "flagpole\n"
+ "graceful\n"
+ "grateful\n"
+ "homemade\n"
+ "homework\n"
+ "housefly\n"
+ "kickball\n"
+ "kingfish\n"
+ "knockout\n"
+ "knothole\n"
+ "lipstick\n"
+ "lunchbox\n"
+ "newscast\n"
+ "nickname\n"
+ "peaceful\n"
+ "sailboat\n"
+ "saturday\n"
+ "shameful\n"
+ "sidewalk\n"
+ "snowball\n"
+ "splendid\n"
+ "suitcase\n"
+ "sunblock\n"
+ "sunshine\n"
+ "swimming\n"
+ "thankful\n"
+ "thinnest\n"
+ "thursday\n"
+ "whatever\n"
+ "whenever\n"
+ "windmill\n"
+ "american\n"
+ "possible\n"
+ "suddenly\n"
+ "airplane\n"
+ "alphabet\n"
+ "bathroom\n"
+ "favorite\n"
+ "medicine\n"
+ "december\n"
+ "dinosaur\n"
+ "elephant\n"
+ "February\n"
+ "football\n"
+ "forehead\n"
+ "headache\n"
+ "hospital\n"
+ "lollipop\n"
+ "november\n"
+ "outdoors\n"
+ "question\n"
+ "railroad\n"
+ "remember\n"
+ "sandwich\n"
+ "scissors\n"
+ "shoulder\n"
+ "softball\n"
+ "tomorrow\n"
+ "upstairs\n"
+ "vacation\n"
+ "restroom";
addAll(Arrays.asList(w.split("\\s+")));
}
};
Some points to consider:
String c = existingGuesses.get(0); //trying to get the first character
gets the first word in a list of words, not the first character.
To get the first character in a String you can do this:
char c = newguess.getCharAt(0);
Then you can search through the list for words starting with that character. Next you do not want to remove words that contain the character, you want to remove words that start with the character.
Also, you want to get each item from the iterator one at a time:
while(iterator.hasNext()){
String w = iterator.next(); //get the next word in the iterator here
//process w here
}
You seem to want to find if the characters correspond. That is, if the guess is "foo" then you want to remove all words that start with f, and all words that has the second character o and all words that have the third character o. That seem a little strange so you may want to check your logic.
Your method seem to be referring to some global variables and that could be causing you some confusion.

Categories