This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am working on a homework about arrays and while loop in java.
The question is to create a method called public int getPopulation(String province) which returns the population of the province. If there is no such province, return a constant called NO_SUCH_PROVINCE, which is an int set to -1. But I cannot get what I want.
public class Country {
public static final int ON = 0;
public static final int QC = 1;
public static final int BC = 2;
public static final int AB = 3;
public static final int MB = 4;
public static final int NO_SUCH_PROVINCE = -1;
private String[] provinces;
private int[] population;
public Country() {
provinces = new String[5];
provinces[0] = "Ontario";
provinces[1] = "Quebec";
provinces[2] = "British Columbia";
provinces[3] = "Alberta";
provinces[4] = "Manitoba";
population = new int[5];
population[ON] = 12851821;
population[QC] = 7903001;
population[BC] = 4400057;
population[AB] = 3645257;
population[MB] = 1208268;
}
public int getPopulation(String province) {
int i = 0;
int temp = 0;
while(i < provinces.length) {
if(province == provinces[i]) {
temp = population[i];
}else {
temp = NO_SUCH_PROVINCE;
}
i++;
}
return temp;
}
There is an issue with your search algorithm. It keeps going after it finds the solution and then overwrites the correct value. This here, when it finds the value, immediately returns the value and leaves the method. If it cannot find any value, it then returns NO_SUCH_PROVINCE.
The other issue is that noted by Scary Wombat, which is that your code does not compare Strings correctly to find a match.
public int getPopulation(String province) {
for (int i = 0; i < provinces.length; i++) { // For objects, always use .equals()
if (province.equals(provinces[i])) { return population[i]; }
}
return NO_SUCH_PROVINCE;
}
Of course, this would be much simpler if one could simply use a HashMap<String, Integer> that stores all the data like a dictionary.
Related
This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
Closed 3 months ago.
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
int[] pascal;
char[] Larray;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
im trying to do this code but pascal, keeps returning as null, when I declare it outside the constructor;
ive also tried this...
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
and I get this error
sierpinski.java:8: error: cannot find symbol
System.out.println(String.valueOf(s1.pascal));
^
symbol: variable pascal
location: variable s1 of type sierpinski
1 error
error: compilation failed
saying it cannot find symbol, any solutions and does anyone know how to fix this??
thanks
tried declaring the variable at the top, but I have no clue how to get this to work, any ideas?
Constructors are essentially methods.
sierpinski(int row) { // this is a constructor
this.row = row; // this sets a field.
int[] pascal = new int[row+1]; // this creates a new local variable
// constructor ends, and with it, all local variables GO AWAY
}
You want to declare a field. You already have one (row), and you already set it (this.row = row). If you want pascal to still exist when the constructor ends, it needs to be a field and not a local:
public Sierpinski {
private int row;
private int[] pascal;
public Sierpinski(int row) {
this.row = row;
this.pascal = new int[row];
}
}
The goal of the application is as following: I want to create objects (airplanes) of the class "Flugzeug" (German word for airplane). I want to create an array which refers to the different attributes of the objects.
The problem is (as far as I know) that one single array can only refer to variables of the exact same type.
How can I change my program that it works? Is it inevitable to create an array for each attribute (e.g. for each different type of variable)?
The code:
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug [] airline = new Flugzeug [4];
for (int i = 0; i < 4; i=i+1){
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[0].idNumber = "1";
airline[0].seats = "165";
airline[0].velocity = "890";
airline[0].range = "12600";
airline[1].type = "Boeing 747";
airline[1].idNumber = "2";
airline[1].seats = "416";
airline[1].velocity = "907";
airline[1].range = "12700";
airline[2].type = "Avro RJ 85";
airline[2].idNumber = "3";
airline[2].seats = "93";
airline[2].velocity = "760";
airline[2].range = "2200";
airline[3].type = "Airbus 380";
airline[3].idNumber = "4";
airline[3].seats = "516";
airline[3].velocity = "907";
airline[3].range = "12000";
}
for (int i=0; i < 4; i=i+1) {
airline[i].printInfo();
double time = airline[i].getTime(6320); //distance from Zurich to New York
System.out.println("duration: " + time + " h");
int capacity = airline[i].getCapacity(365);
System.out.println("capacity: " + capacity + " passengers / year");
}
}
}
public class Flugzeug {
String type;
int idNumber;
int seats;
double velocity;
double range;
double distance;
int days;
public void printInfo() {
System.out.println("type: " + this.type);
System.out.println("ID-number: " +this.idNumber);
System.out.println("seats: " + this.seats);
System.out.println("velocity: " + this.velocity);
System.out.println("range: " + this.range);
}
public double getTime (double dist) {
double result = 0;
result = dist / velocity;
double time = result;
return time;
}
public int getCapacity(int days) {
int capacity = seats * days;
return capacity;
}
}
The core of your problem is this:
one single array can only refer to variables of the exact same type.
That is correct (or mostly correct, all elements of an array must have a common base type, but that's not a relevant distinction right now).
But the type inside of your array is Flugzeug, not String!
So each element of the array must be a Flugzeug. That doesn't mean that the fields of that class have to all share a single type (and indeed, as you posted, they don't).
Look at this line:
airline[0].idNumber = "1";
this is almost correct, but since idNumber is an int you must assign it an int value (such as 1) instead:
airline[0].idNumber = 1;
The second (mostly unrelated) problem is that you try to access all 4 Flugzeug instances inside of the loop that creates them. That means when you try to access the second instance after just having created the first one (only!) it will crash:
Replace this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
}
with this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
}
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
if some type like int,double,long... was used " " ,They almost all become String type
I found two problems with your code.
First, you have declared idNumber as int int idNumber; but while assigning the value you are inserting a string value airline[0].idNumber = "1";.
NOTE: "1" is a string not integer.
The solution here would be airline[0].idNumber = 1;
You need to assign same type of values to every variable as they are declared.
And second, you are creating multiple objects in the loop airline[i] = new Flugzeug (); but overwriting the same single object (stored in the 0th position of the array) everytime. I would suggest to do,
airline[i].type = "A320";
airline[i].idNumber = 1; // Again this should not be "1"
airline[i].seats = 165; // And this should not be "165"
airline[i].velocity = 890; // Same is applicable here
airline[i].range = 12600; // and here
The problem is the variables are not only String type but ints and doubles as well. You need to assign the correct type. In addition you shouldn't access class variables like that, make them private create a constructor with getters and setters.
public class Flugzeug {
private String type;
private int idNumber;
private int seats;
private double velocity;
private double range;
private double distance;
private int days;
public Flugzeug(String type, int idNumber, int seats, double velocity, double range) {
this.type = type;
this.idNumber = idNumber;
this.seats = seats;
this.velocity = velocity;
this.range = range;
}
public double getDistance() {
return this.distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug[] airline = new Flugzeug [4];
airline[0] = new Flugzeug("A320", 1, 165, 890, 12600);
airline[1] = new Flugzeug(...);
}
}
public static int arraysize=1;
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][]=new String[arraysize][3];
public static int a=0;
public void isiData(String kategori, String buku, String penulis){
this.buku[a][0]=kategori;
this.buku[a][1]=buku;
this.buku[a][2]=penulis;
arraysize++;
a++;
}
Hi guys I tried to increase my array length every time I call a method named "isiData", but it didn't work. I already checked the increment, but nothing wrong with it. Is there any way to increase its length every time I use the method? I want to make a simple way to input book, category, and its author using array.
You cannot increase the size of array.
There are 3 approaches to solve this problem:
Use ArrayList as suggested by others.
You can create another temp array of size one greater than the previous array and then copy the temp array to already created array.
You can use the copyOf(array, size) function of Arrays in Java
For example:
previousArray = Arrays.copyOf(previousArray , arraysize + 1);
arraysize += 1
Just try this Approach:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
/**
*
* #author Maverick
*/
public class Buku {
public static int arraysize;
public String namabuku;
public String penulis;
public String Kategori;
public List<List<String>> bukuList = new ArrayList<List<String>>();
public static void main(String[] args) {
Buku n = new Buku();
for (int i = 0; i < 5; i++) {
n.isiData("ab" + i, "cd" + i, "ef" + i);
}
n.arraysize = n.bukuList.size();
for (int i = 0; i < n.bukuList.size(); i++) {
System.out.println(n.bukuList.get(i).toString());
}
}
public void isiData(String kategori, String buku, String penulis) {
bukuList.add(Arrays.asList(kategori, buku, penulis));
}
}
Output:
[ab0, cd0, ef0]
[ab1, cd1, ef1]
[ab2, cd2, ef2]
[ab3, cd3, ef3]
[ab4, cd4, ef4]
You have to call new array to change the size of an array. I assume this is an exercise to practice using an array, so I'm going to avoid the classes like Arrays and System in the isiData method. You should look at those classes though.
So something like this:
public class BukuTest
{
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][] = new String[ 0 ][ 3 ];
public void isiData( String kategori, String buku, String penulis )
{
String[][] temp = this.buku;
final int len = temp.length;
this.buku = new String[ len + 1 ][];
for( int i = 0; i < len; i++ )
this.buku[i] = temp[i];
this.buku[len] = new String[ 3 ];
this.buku[len][0] = kategori;
this.buku[len][1] = buku;
this.buku[len][2] = penulis;
// not needed
// arraysize++;
// a++;
}
public static void main(String[] args) {
BukuTest b = new BukuTest();
b.isiData( "test1", "test2", "test3" );
b.isiData( "test4", "test5", "test6" );
b.isiData( "test7", "test8", "test9" );
System.out.println(b);
}
#Override
public String toString()
{
return "BukuTest{" + "namabuku=" + namabuku + ", penulis=" + penulis +
", Kategori=" + Kategori + ", buku=" +
Arrays.deepToString(buku) + '}';
}
}
Using an ArrayList is definitely the way to go here as others have commented and displayed but, if you are absolutely bent on using a Two Dimensional String Array then this can be done with a custom method conveniently named redimPreserve() as I have shown below.
As #Jdman1699 had mentioned in his comment under your post, this is a very inefficient way of doing this sort of thing especially for larger arrays but since you asked, here is how it can be done:
// YOUR METHOD:
public int arraysize = 1;
public String[][] buku = new String[arraysize][3];
public void isiData(String kategori, String buka, String penulis){
// I have renamed the buku argument for this method to buka
// since you can not have a parameter variable named the
// same as a Class Global variable.
buku = redimPreserve(buku, arraysize, 3);
buku[arraysize-1][0] = kategori;
buku[arraysize-1][1] = buka;
buku[arraysize-1][2] = penulis;
arraysize++;
}
// THE redimPreserve() METHOD:
public static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
int newCol = 0;
if (newColSize.length != 0) { newCol = newColSize[0]; }
// The first row of your supplied 2D array will always establish
// the number of columns that will be contained within the entire
// scope of the array. Any column value passed to this method
// after the first row has been established is simply ignored.
if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
if (newCol == 0 && newRowSize <= 1) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Column dimension provided for 2D Array!\n");
}
if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Row dimension provided for 2D Array!\n");
}
String[][] tmp = new String[newRowSize][newCol];
if (yourArray.length != 0) {
for(int i = 0; i < yourArray.length; i++) {
System.arraycopy(yourArray[i], 0, tmp[i], 0, yourArray[i].length);
}
}
return tmp;
}
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 9 years ago.
Improve this question
Is there anyway I could return an array of strings from an array of pairs? I'm guessing it's something to do with hashmap since two values are involved. Any simple example with some explanation would help :)
As pointed out by #dasblinkenlight, if the input is (y,3),(t,2) and I want the output as "yPP","tP" where the string should have the length of the numerical value given. and so after taking the character, the rest of the length is to be filled by P.
Suppose I've got the static method,
public static Line[] get(Couple[] temp)
I need to complete it so that my main method would produce the following result:
get (new Couple[]{new Couple(āeā,4), new Couple(ānā,2)})
should return the array of Strings
{"ePPP", "nP"}
Hope this helps :)
class Pair{
public Pair(String st1,String st2){
string1=str;
string2=str;
}
private String string1;
private String string2;
// + getters and maybe setters for strings;
}
Later on create simple Pair[] and do whatever you want
With a Pair class implemented as
class Pair {
private final String s;
private final int i;
public Pair(String s, int i){
this.s = s;
this.i = i;
}
public String getS() {
return s;
}
public int getI() {
return i;
}
}
Initialize the Pair[] and invoke a converter method as
Pair[] pairArr = new Pair[2];
pairArr[0] = new Pair("Y", 3);
pairArr[1] = new Pair("T", 2);
System.out.println(Arrays.toString(convertPairsToStrArray(pairArr, "P")));
Output :
[YPP, TP]
Here's a sample converter implementation:
private static String[] convertPairsToStrArray(Pair[] pairArr, String padStr) {
String[] strArr = null;
if (pairArr != null) {
strArr = new String[pairArr.length];
for (int i = 0; i < pairArr.length; i++) {
String s = pairArr[i].getS();
StringBuilder sb = new StringBuilder();
if (s != null) {
sb.append(s);
int j = 0;
if ((j = pairArr[i].getI() - s.length()) > 0) {
while (j-- > 0) {
sb.append(padStr);
}
}
}
strArr[i] = sb.toString();
}
}
return strArr;
}
Like many things, the question contains the answer.
Create a class to hold the pairs. Add a method, to that class, to produce the desired output. Here is some code:
Pairzor.java:
public class Pairzor
{
private final static char FILL_CHARACTER = 'P';
private final char theChar;
private final int theCount;
public Pairzor(
final char newChar,
final int newCount)
{
theChar = newChar;
theCount = newCount;
}
public final String blammy()
{
StringBuilder buffer = new StringBuilder();
buffer.append(theChar);
for (int count = 1; count < theCount; ++count)
{
buffer.append(FILL_CHARACTER);
}
return buffer.toString();
}
}
Main.java
public class Main
{
/**
* #param args
*/
public static void main(String[] args)
{
Pairzor one = new Pairzor('y', 3);
Pairzor two = new Pairzor('t', 2);
System.out.println(one.blammy());
System.out.println(two.blammy());
}
}
I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.