Arrays in Java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
so i need to find a way to get my program to hold a string of names that the user is going to input. the array will hold a total of five names and is going to output all the information back to the user with their entered names. I am using a single main class.
so far this is what i have:
import java.util.Scanner;
public class Names {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String [] name = new String [5];
for (int i = 0; i < 5; i++){
System.out.println("Enter name: ");
String UserNames = input.nextLine();
name[i] = UserNames;
}
}
}
I need to know if this is storing the names correctly in the array? I am very new to java and need some insight from the pros. Also if i want to get the names to repeat back to them will it look like this
{
System.out.println(" The names you entered are:" + UserNames );
}
Thanks for any help I can get.

i need to know if this is storing the names correctly in the array?
So, print the array once you've filled it with Arrays.toString()

It seems you're doing it right.
To print them, you need to loop through the array.
for (int i = 0; i < name.length; i++){
System.out.println(name[i]);
}

as suggested by Kepani you can try Arrays.toString(arrayVarName)
public static void main(String[] args)
{
String [] arx = {"alpha", "beta", "gamma", "penta", "quad"};
System.out.println(arx); // returns object hashcode and not the strings stored
System.out.println(Arrays.toString(arx));
}
in case you do not know whether you will be getting 5 inputs or more you can try arraylist
public static void main(String[] args)
{
ArrayList<String> strList = new ArrayList<String>();
strList.add("alpha");//Construct would be strList.add(input)
strList.add("beta");
strList.add("gamma");
strList.add("penta");
strList.add("quad");
System.out.println(strList);
System.out.println(strList.toString());
}
as you would realize due to the use of generics ArrayList.toString() return the complete list of strings store

Related

Sorting ArrayList Collections.sort not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I can see that this topic has been heavily discussed, however, I was not able to find an answer to my problem within previous discussions. That being said, I have a very simple problem where I want to ask a user to input a list of cities. After being entered, I am storing the list in an ArrayList cities and using collections.sort to sort them. For some reason, collections.sort is not sorting my ArrayList. Example: User input is "Atlanta, Washington DC, New York". My output, when running the program, is unsorted.
public class CitySortDemo {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("enter as many cities as you can!");
cities.add(input.nextLine());
Collections.sort(cities);
for (int i = 0; i < cities.size(); i++){
System.out.println(cities.get(i));
}
}
}
Your code adds a single string to the collection, "Atlanta, Washington DC, New York". A collection with only one entry is unaffected by sorting. :-)
You probably meant to break that string up, perhaps by splitting it on a comma:
cities.addAll(Arrays.asList(input.nextLine().split("\\s*,\\s*")));
Live Example
That splits the one string into an array of them on a comma optionally preceded and/or followed by whitespace, and adds them all to the collection.
Either you can ask the user how many cities are expected to sort or specify a character that when it is seen, stop taking input and sort them. In this your code, it just takes one line as a string. For example, it takes cities until the user enters the specifier character in which the code is ! then sort.
import java.util.*;
class CitySortDemo {
public static void main(String[] args) {
final String specifier = "!";
String str;
ArrayList<String> cities = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("enter as many cities as you can!");
str = input.nextLine();
while (! str.equals(specifier)) {
cities.add(str);
str = input.nextLine();
}
Collections.sort(cities);
cities.forEach(System.out::println);
}

Hello I want, I make a program that stores names and stop when writing"stop" ends and the program displays the names stored in this [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I make a program that stores names and stop when writing"stop" ends and the program displays the names stored in this ......This code displays the last name you've entered i want to display all names
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter The name : ");
String name = sc.next();
while (!"stop".equals(name)){
System.out.println("please entrr new name : ");
name = sc.next();
}
System.out.println(name);
}
}
The problem with storing data is that you actually have to store the data somewhere ;). You can use an Array of Strings or pretty much any kind of Collection. In this case I'd say simple ArrayList is the best. So you create the list:
List<String> names = new ArrayList<>();
Then you append elements to the list by using add() method. For example:
names.add(name);
You can easily print an output with build in toString() method like this:
System.out.println(names);
or iterate through the list and print them yourself. Note that you probably don't want to store the "stop" String in your list.
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>(); // declaring dynamic array
Scanner sc = new Scanner(System.in);
System.out.println("Enter The name : ");
String name = sc.next();
int i = 0;
while (!"stop".equals(name)) {
System.out.println("please entrr new name : ");
name = sc.next();
a.add(name); // each time you add your name to the array and store
i++;
}
for (int j = 0; j < a.size(); j++)
System.out.println(a.get(j));
}
Check this it should work because in your code you do not store the names anywhere and each time you just overwrite it but with ArrayList you store your names and then you can use it anywhere.

Identifing the single largest number occurring in a file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's assume a text file is a Math text book. How should I code to find out the largest number in that file? I'm aware of using StringTokens, parseLong, split, etc. But I can't figure out a proper way to combine them.
To be precise, let's say that text has something like:
Chapter 3.5
Million has 6 zeros. Ex. 6,000,000
Billion has 9 zeros. Ex. 9,000,000,000
Trillion has 12 zeros. Ex. 8,000,000,000,000
The largest number is 8000000000000. How do I extract that?
Thanks in advance.
Use the Scanner interface. This code assumes you pass in the file path as the first argument. The Scanner interface handles commas in numbers. I use BigInteger to handle any size number.
public static void main (String[] args) throws java.lang.Exception
{
BigInteger biggestNumber = null;
Scanner s = new Scanner(new FileReader(args[0]));
while( s.hasNext() ){
if( s.hasNextBigInteger() ){
BigInteger number = s.nextBigInteger();
if( biggestNumber == null || number.compareTo(biggestNumber) == 1 ){
biggestNumber = number;
}
}
else {
s.next();
}
}
System.out.println("Biggest Number: " + biggestNumber.toString());
}
You can play with an online example at: http://ideone.com/zKI5rM . It doesn't read from a file but uses a string in the code instead.
One place this would fail is if the book splits large numbers across lines. I'm not sure what your source material is, but that is something to keep in mind.
Store the largest number seen so far (initially, negative infinity), then go through the entire file extracting each number and if it's greater than the largest number you've stored, store it. At the end, the number stored is the largest number. Use double rather than long to account for very large numbers and noninteger numbers. The simple way to find all integers is to use a Scanner, feeding next() into parseDouble(...) and comparing anything that doesn't throw a NumberFormatException.
The easiest way would be to parse the text file line by line.
You can do this using regular expressions to see if you have any number formats located in the current line. If you do then you can check to see if it's larger than the previously found number.
Here is an excellent tutorial on regular expressions if you haven't came across them yet.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
You can use BigInteger
public class Test {
public static void main(String[] arg) {
String line = "215,485,454,648,464";
String line1 = "5,454,546,545,645";
List<BigInteger> list = new ArrayList<BigInteger>();
list.add(new BigInteger(line.replaceAll(",", "")));
list.add(new BigInteger(line1.replaceAll(",", "")));
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}
}
Output: largest: 215485454648464
For your situation
public static void main(String[] args){
Scanner input = new Scanner(new File("yourFile.txt");
List<BigInteger> list = new ArrayList<BigInteger>();
while (input.hasNextLine()){
String line = input.nextLine();
String[] tokens = line.split("\\s+");
String number = token[5].trim(); // gets only the last part of String
list.add(new BigInteger(line.replaceAll(",", "")));
}
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}

I have to write a code that uses classes for DNA, RNA, and Protein. Im stuck on the first part [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to take a users input int as length of the dna a sequence. Im trying to return the numberString but i get an issue with my array every time
Driver
import java.util.Scanner;
public class GenBank1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Enter a desired DNA sequence length, between 1 and 10 please:");
int inputLength = in.nextInt();
System.out.println(inputLength);
System.out.println(DNA1.toNumString(inputLength));
int[] baseId = new int[inputLength];
for(int i=0;i<=baseId.length;i++){
baseId[i]=inputLength;
int rndmr = (int)(4.0*Math.random());
baseId[i]-=rndmr;
System.out.print(baseId[i]+1 + ",");
}
}
}
for(int i=0;i<=baseId.length;i++)
You should probably do
for(int i=0;i<baseId.length;i++)
since, in an array with (say) 10 entries, they will have indices 0 to 9. Trying to look up array[10] will throw an exception.
Without knowing what the DNA1 class is and what the function of the program is, I would not be able to comment futher. However yes, you will experience ArrayIndexOutOfBoundsException to correct this the following should work
import java.util.Scanner;
public class GenBank1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Enter a desired DNA sequence length, between 1 and 10 please:");
int inputLength = in.nextInt();
System.out.println(inputLength);
System.out.println(DNA1.toNumString(inputLength));
int[] baseId = new int[inputLength];
for(int i=0;i<baseId.length;i++){
baseId[i]=inputLength;
int rndmr = (int)(4.0*Math.random());
baseId[i]-=rndmr;
System.out.print(baseId[i]+1 + ",");
}
}
}
Your ending clause for your FOR loop wanted to go from 0 -> length which would be wrong as you will go over the Array index.

Purchase Java with Arrays [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm Raymond, computer programming student. I have problem about arrays. Are instructor ask us to do a program that goes like this.
in this codes below. i want to display the same item code i entered. but the problem is that once i answered yes and input again number, the only thing that display is the last number or code i enter.
import java.util.Scanner;
public class _TindahanArray {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String ans, i = "";
int x;
do {
System.out.print("Item code:");
i += a.next();
System.out.print("\nAnother item? [y/n]:");
ans = a.next();
} while (ans.equals("y"));
String[] code = new String[2];
for (x = 0; x < 1; x++) {
code[x] = i;
System.out.print(code[x]);
code[x] = "\n";
System.out.print(code[x]);
}
}
}
As you shown some efforts, I just want to update your code.
Your code is fine for only printing two item codes.
Use collection ArrayList to store the item codes. I am using String array list.
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayTest {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String ans;
ArrayList<String> itemCodeList = new ArrayList<String>(); //create array list
do{
System.out.print("Item code:");
itemCodeList.add(a.next()); //add item code into array list
System.out.print("\nAnother item? [y/n]:");
ans = a.next();
}while(ans.equals("y"));
for (String code : itemCodeList)
{
System.out.println(code);
}
}
}
ArrayList example

Categories