Finding the largest string in the second column of a 2d array - java

I have a 2d array and I'm trying to find the largest string only in the second column of the 2d array, but for some reason it only gives me the first string in the 2nd column even if there is a bigger string. Here's what I have:
class Main{
public static void main(String[] args) {
String[][] data = {
{"Jeep", "Wrangler", "35000"},
{"Honda", "civic", "25000"},
{"Toyota", "Corolla", "22000"}
};
LargestName(data);
}
public static void LargestName(String[][] a){
String largestN = a[0][1];
for(int i = 0; i < a.length; i++){
if(largestN.compareTo(a[i][1])<0){
largestN = a[i][1] + "";
}
}
System.out.println(largestN);
}
}
Again, I'm trying to compare the strings only in the second column of the 2d array but with what I have it only gives me the first string of the 2nd column "Wrangler", even if there is a larger string in the 2nd column. Please help

I cannot see a flaw in the code. So look at the definition of 'largest string': It is possible that the code really returns exactly that value that you chose in the beginning.
This can be easily tested by choosing a different start value.
On top of that you could add more System.out.println, or even better use a debugger to step through your code. This will give you a very good understanding of how the JVM executes your code.

You need to comapre length, compareTo is not good choice, please look what are you trying to do:
System.out.println("Wrangler".compareTo("civic"));
System.out.println("civic".compareTo("Corolla"));
System.out.println("Corolla".compareTo("Wrangler"));
result:
-12 32 -20

Related

How do I access and manipulate individual values in a String Array when using a while and for loop

Very new to Java: Trying to learn it.
I created an Array and would like to access individual components of the array.
The first issue I am having is how to I print the array as a batch or the whole array as indicated below? For example: on the last value MyValue4 I added a line break so that when the values are printed, the output will look like this: There has to be a better way to do this?
MyValue1
MyValue2
MyValue3
MyValue4
MyValue1
MyValue2
MyValue3
MyValue4
The next thing I need to do is, manipulate or replace a value with something else, example: MyValue with MyValx, when the repeat variable is at a certain number or value.
So when the repeat variable reaches 3 change my value to something else and then change back when it reaches 6.
I am familiar with the Replace method, I am just not sure how to put this all together.
I am having trouble with changing just parts of the array with the while and for loop in the mix.
My Code:
public static String[] MyArray() {
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
return MyValues;
}
public static void main(String[] args) {
int repeat = 0;
while (repeat < 7) {
for (String lines : MyArray()) {
System.out.println(lines);
}
repeat = repeat + 1;
if (repeat == 7) {
break;
}
}
}
Maybe to use for cycle to be shorter:
for (int i = 0; i < 7; i++) {
for (String lines : MyArray()) {
// Changes depended by values.
if (i > 3) {
lines = MyValx;
}
System.out.println(lines); // to have `\n` effect
}
System.out.println();
}
And BTW variables will start in lower case and not end withenter (\n). So use:
String myValues[] = {"MyValue1", "MyValue2", "MyValue3", "MyValue4"};
instead of:
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
and add System.out.println(); after eache inside cycle instead of this:
MyValues[n] = "value";
where n is the position in the array.
You may consider using System.out.println() without any argument for printing an empty line instead of inserting new-line characters in your data.
You already know the for-each loop, but consider a count-controlled loop, such as
for (int i = 0; i < lines.length; i++) {
...
}
There you can use i for accessing your array as well as for deciding for further actions.
Replacing array items based on a number in a string might be a bit trickier. A regular expression will definitely do the job, if you are familiar with that. If not, I can recommend learning this, because it will sure be useful in future situations.
A simpler approach might be using
int a = Integer.parseInt("123"); // returns 123 as integer
but that only works on strings, which contain pure numbers (positive and negative). It won't work with abc123. This will throw an exception.
These are some ideas, you might try out and experiment with. Also use the documentation excessively. ;-)

Spanish Number Method Parameters & Loops

have to do an exercise called SpanishNumbers. Create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are:
1 uno, 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
package chapter7java;
import java.util.Scanner;
/**
*
* #author Eric
*/
public class SpanishNumbers {
public static void spanNum(int num, String word) {
for (int i = 1; i<= num; i++) {
if (num = 1) {
System.out.println("Uno");
}
}
}
public static void main (String [] args) {
for (int i = 1; i<=10; i++) {
System.out.println(i);
}
}
}
So before you freak out, I'm having trouble even starting this thing so maybe give me some tip hows I can do what it asks, not finish the work necessarily. What I posted was just crap so just let me know how I can go about starting this. Thanks in advance! This is beginner java so keep it simple.
The function spanNum needs only an int as a parameter. Remove the String parameter passed to it. Replace
public static void spanNum(int num, String word) {
with
public static void spanNum(int num) {
The spanNum function is supposed to print the Spanish for one number (the one passed in parameter num). So there should be no loop. Also = is an assignment statement, not a comparison operator. The comparison operator is ==. So the statement to test if num is equal to 1 would be if(num == 1).
In the main, you could call spanNum in the loop for all values of i.
You're going to want to create an array to hold your spanish numbers.
String[] numbers = {"uno", "dos", "tres", ......}
Declare that inside your spanNum method; you then just print out the value at index i to convert it into spanish. Just remember that array indices start at 0, so you'll need to shift
your index by one.
First of all, the line if(num = 1) should be if(num == 1) since = assigns and == compares. Second, when you are planning to take one number and do different things based on its value, a switch block may be more useful than multiple if...else if blocks. Third, in your main method, you are simply outputting the loop control variable, i, each time instead of calling spanNum().

Change an array of ints to a series of strings

I'm trying to achieve the following output from the following input:
Sample input:
3 4
2 1
4 5
-1
Sample output:
7
3
9
So far, I have my program doing all of the math and I'm getting it to terminate when the user puts in a negative number. My problem is that I'm having trouble getting it to print in the above format. A sample of my input/output is below:
9 9
8 8
9 -8
[18, 16]
Here's my code so far:
import java.util.ArrayList;
import java.util.Scanner;
public class sums{
public static void main(String[]args){
int addition = 0;
int previous = 0;
ArrayList<String> sums = new ArrayList<String>();
String sumsy = new String("");
for (int i=0; i<=i;){
Scanner in = new Scanner(System.in);
previous = in.nextInt();
if (previous<0){
break;
}
else {
addition = in.nextInt();
if (addition<0) {
break;
}
else {
addition += previous;
sums.add(addition+"");
}
}
} System.out.println(sums);
}
}
I believe the answer lies in somehow using a delimiter ("/n") somewhere, and getting my array of ints to print out just as strings.
I'm sorry, these small things elude me completely. Can anyone point me in the right direction?
Thank you!
-Helen
for (String sum : sums) System.out.println(sum)
use this instead of
System.out.println(sums)
System.out is a PrintStream object, and its println methods are overloaded for a variety of different types.
In this case, because sums is an ArrayList, you're calling println(Object x), which works by calling String.valueOf(x) on the passed object (which in turn calls x.toString() if x does not equal null), and printing the resulting String.
Essentially, when you pass something other than a String or a primitive to println, you're delegating the details of how it gets printed to the class of the object. In this case, since ArrayList is a library class, you have no control over this.
To make it work the way you want, you need to iterate over the values in sums, something like:
for (String someSum : sums) {
System.out.println(someSum);
}
If you're not familiar with that loop syntax, see the second half of this page: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
sums is an list of strings, not a string, so printing it isn't going to give you what you want. You have two options, you could do
for(String i : sums){ System.out.println(i); }
or you could make sums a stringbuilder and do sums.append(addition) and then System.out.println(sums.toString())
Do you really have to use an ArrayList? IMO, this makes it much more complicated than necessary. From your example input, it appears that you simply want to sum each pair of numbers. This doesn't seem to require an array. You could just add the two numbers together and immediately print out the result.

two dimensional array in java - difficulties

I'm used to python and django but I've recently started learning java. Since I don't have much time because of work I missed a lot of classes and I'm a bit confused now that I have to do a work.
EDIT
The program is suppose to attribute points according to the time each athlete made in bike and race. I have 4 extra tables for male and female with points and times.
I have to compare then and find the corresponding points for each time (linear interpolation).
So this was my idea to read the file, and use an arrayList
One of the things I'm having difficulties is creating a two dimensional array.
I have a file similar to this one:
12 M 23:56 62:50
36 F 59:30 20:60
Where the first number is an athlete, the second the gender and next time of different races (which needs to be converted into seconds).
Since I can't make an array mixed (int and char), I have to convert the gender to 0 and 1.
so where is what I've done so far:
public static void main(String[] args) throws FileNotFoundException {
Scanner fileTime = new Scanner (new FileReader ("time.txt"));
while (fileTime.hasNext()) {
String value = fileTime.next();
// Modify gender by o and 1, this way I'm able to convert string into integer
if (value.equals("F"))
value = "0";
else if (value.equals("M"))
value = "1";
// Verify which values has :
int index = valor.indexOf(":");
if (index != -1) {
String [] temp = value.split(":");
for (int i=0; i<temp.length; i++) {
// convert string to int
int num = Integer.parseInt(temp[i]);
// I wanted to multiply the first number by 60 to convert into seconds and add the second number to the first
num * 60; // but this way I multiplying everything
}
}
}
I'm aware that there's probably easier ways to do this but honestly I'm a bit confused, any lights are welcome.
Just because an array works well to store the data in one language does not mean it is the best way to store the data in another language.
Instead of trying to make a two dimensional array, you can make a single array (or collection) of a custom class.
public class Athlete {
private int _id;
private boolean _isMale;
private int[] _times;
//...
}
How you intend to use the data may change the way you structure the class. But this is a simple direct representation of the data line you described.
Python is a dynamically-typed language, which means you can think of each row as a tuple, or even as a list/array if you like. The Java idiom is to be stricter in typing. So, rather than having a list of list of elements, your Java program should define a class that represents a the information in each line, and then instantiate and populate objects of that class. In other words, if you want to program in idiomatic Java, this is not a two-dimensional array problem; it's a List<MyClass> problem.
Try reading the file line by line:
while (fileTime.hasNext())
Instead of hasNext use hasNextLine.
Read the next line instead of next token:
String value = fileTime.next();
// can be
String line = fileTime.nextLine();
Split the line into four parts with something as follows:
String[] parts = line.split("\\s+");
Access the parts using parts[0], parts[1], parts[2] and parts[3]. And you already know what's in what. Easily process them.

Sorting string array in Java

There is an example in my textbook for how to sort string arrays, but I am having a hard time understanding the logic of the code. We have the following array:
String[] words = {"so", "in", "very", "every", "do"};
The method itself is as follows:
public static void sortArray(Comparable[] compTab) {
for (int next=1; next < compTab.length; next++) {
Comparable value = compTab[next];
int this;
for (this = next; this > 0 && value.compareTo(compTab[this-1]) < 0; this--) {
compTab[this] = compTab[this-1];
}
compTab[this] = value;
writeArray(next + " run through: ", compTab);
}
}
This last writeArray call results in the following text being printed for first run through: "1. run through: in so very every do"
OK. Like I said, I have some problems with the logic in this code. If we go through the loop for the first time, this is what I see happening:
We have: Comparable value = compTab[1]. This means that value = "in".
We start the inner loop with this = next (which == 1). Thus, Java will only go through the inner loop once. It turns out that for this first run value.compareTo(compTab[this-1]) is indeed less than 0. Thus we have: compTab[1] = compTab[0]. This means that the word that used to be in position [1] is now replaced with the word that used to be in position [0]. Thus, we now have the word "so" in position [1] of the array.
The next step in the method is: compTab[this] = value. This is where I get confused. This tells me that since this = 1, we here get compTab[1] = value. However, earlier in the method we defined value = "in". This tells me that position [1] in the array yet again assumes the word "in".
The way I see this, the final print out should then be:
"1. run through: so in very every do".
In other words, the way I follow the logic of the code, the final print out of the array is just the same as it was before the method was implemented! Clearly there is some part of my logic here which is not correct. For instance - I don't see how the word that used to be in position [1] is now in position [0]. If anyone can help explain this to me, I would be extremely grateful!
The issue is within the following statement:
The next step in the method is: compTab[this] = value. This is where I
get confused. This tells me that since this = 1, we here get
compTab[1] = value. However, earlier in the method we defined value =
"in". This tells me that position [1] in the array yet again assumes
the word "in".
Since you ran through the loop once (see your statement 2), also the this-- was executed once and therefore this==0.
public class A {
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
public static void main(String[] args)
{
for(int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if(Array[i].trim().compareToIgnoreCase(Array[j].trim())<0)
{
String temp= Array[j];
Array[j]= Array[i];
Array[i]=temp;
}
}
System.out.print(Array[j]);
}
}
}

Categories