Looping through two separate if statements - java

The code below is a simplified version of a method I am working on for a java project. The method will sort through a list of items(two different categories), in this case 0,s and 1's. The code reads through an array of numbers stops at either 0 or 1 and then prints out both the 0 or one and the string of numbers following the 0 or 1. If a preceding string is a 1 or a zero then it will stop and switch to another if statement. However it only executes each statement once. However there is more in the array that it needs to read through and organize. I would like to set up some sort of loop so that it loops through the set of if statements until it has read through the entire array.
public class tester
{
public static void main(String[] args )
{
String flags[] = {"0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i,j,k,h;
int count = 0;
for (i = 0; i<flags.length; i++)
{
if (flags[i].equals("0"))
{
for (j=0; !flags[j].equals("1") ; j++)
{
count = j+1;
array[j] = flags[j];
zeros[j] = flags[j];
}
} else
if (flags[count].equals("1"))
{
j = 0;
for(k=count; !flags[k].equals("0");k++)
{
array[k] = flags[k];
j++;
ones[j-1] = flags[k];
}
}
}
for(i=0; i<zeros.length; i++)
{System.out.println(zeros[i]);}
System.out.println();
for(i=0; i<ones.length; i++)
{System.out.println(ones[i]);}
}
}
What it prints out now:
0
23
25
34
null
null
null
null
null
null
null
null
1
9
12
13
null
null
null
null
null
null
null
null

String flags[] = {"9","0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i;
boolean addingZeroes = false;
boolean addingOnes = false;
int zeroCount = 0;
int onesCount = 0;
for (i = 0; i<flags.length; i++) {
if (flags[i].equals("0")) {
zeros[zeroCount] = flags[i];
zeroCount++;
addingZeroes = true;
addingOnes = false;
} else if (flags[i].equals("1")) {
ones[onesCount] = flags[i];
onesCount++;
addingZeroes = false;
addingOnes = true;
} else if (addingZeroes) {
zeros[zeroCount] = flags[i];
zeroCount++;
} else if (addingOnes) {
ones[onesCount] = flags[i];
onesCount++;
}
}
for(i=0; i<zeroCount; i++) {
System.out.println(zeros[i]);
}
System.out.println();
for(i=0; i<onesCount; i++) {
System.out.println(ones[i]);
}
Hey, couple things were wrong. Basically, you need a little state machine where you need to know whether you are in the midst of storing the sequence after a 1 or a 0. I used the boolean values (eg addingZeroes) for that.
Then, you need to separately keep track of your element count (eg zeroCount) for each of the storage arrays. You might have 20 digits after a 0 and just 2 after a 1.
Finally, at the end, your length of your storage arrays is not what you want - you want the amount of values you ended up storing. That's why you got all those "nulls".
One other thing I noticed is that your j value is initialized always to 0 in the 0 block, so you would always be using the lowest values of the start array.

Related

returning the smallest value of an array

I have a method that is supposed to return the smallest value of an array. The array is in the parametre of the method, so you input the values of your own choosing when you make an object of the class. This is the method I have come up with so far:
public class minsteNummer {
public minsteNummer() {
}
public int minsteNummer(Integer[] nummer) {
int minste = 0;
for(int i = 0; i< nummer.length; i++){
if(nummer[i] <= nummer.length) {
minste = i;
System.out.println("Minste nummer er " + minste);
} else if(nummer.length == 0) {
return 0;
}
}
return 0;
}
}
It does not execute the way I want it to, and I cant figure out what exacly it prints, but it is definetly not the smalles number of the array. I have tried with a while loop, but that does not work either.
Does anyone know where the fault in the code is, and how to improve it? I would also like it to just return, not print, the smalles number, but when I try to put "return minste;" in the if-statement, it says "unexpected return value".
Thanks in advance.
There are few places in your code that need attention:
As method scope is public you should always check for invalid input
Should not assign: int minste = 0; as there could be a negative number in a given array
When assign minimum number, should always compare it to the loop current number
if (minste > nummer[i]) minste = nummer[i];
Finally always return your minimum number return minste;
All together:
public static int minsteNummer(Integer[] nummer) {
if (nummer==null || nummer.length == 0) {
throw new IllegalArgumentException("Bad or empty array");
}
int minste = nummer[0];
for (int i = 1; i< nummer.length; i++){
if (minste > nummer[i]) minste = nummer[i];
}
System.out.println("Minste nummer er " + minste);
return minste;
}
It is worth to mention that you could use Java build-in functionality for such a basic task, i.e. sort array in ascending order and get first element:
public static int minsteNummer(Integer[] nummer) {
if (nummer==null || nummer.length == 0) {
throw new IllegalArgumentException("Bad or empty array");
}
Arrays.sort(nummer);
return nummer[0];
}
use streams
Integer[] arrayB = null;
OptionalInt min = Arrays.stream(arrayB).mapToInt(Integer::intValue).min();
public int minsteNummer(Integer[] nummer) {
int minste = Integer.MAX_VALUE;
for(int i = 0; i< nummer.length; i++){
if(nummer[i] < minste ) {
minste = nummer[i] ;
}
if(minste != Integer.MAX_VALUE)
return minste;
else
return 0;
}

Keeping the Value of an Array Outside the method

I am trying to keep the values of my array dates from the Unsorted method, so that it can be used to have another return value in a separate method, that being the Sorted method. I know there would be no trouble in this, but when running the program (which is done using a GUI) the array outside of the Unsorted method is only 1 item long, effectively losing all but one of its items.
I have reason to believe that this is because of the line
while((line = myFile.readLine()) != null){ ...
Because when i try to output the items of the array outside of the while loop in the Sorted function, it also returns only the last item of the array. There is no reason to use split.string here, as I know the Tokenizer will get the job done easily, and the project calls for using the Tokenizer. I would imagine that I could change the way the tokens are added to the array, but I have tried the add function, and it did not work, and when doing so I get "The Method add(String) is undefined for type string"
Here is the example text file(dates.txt):
20161001
20080912,20131120,19980927
20020202,hello
20120104
These dates are structured "yearmonthday" all with a length of 8. the hello is added to ensure that we check for the appropriate items in the text file.
Here is the code:
import java.util.StringTokenizer;
public class Project1{
public static TextFileInput myFile;
public static StringTokenizer myTokens;
public static String[] dates;
public static String line;
public String Unsorted(String date) {
myFile = new TextFileInput("dates.txt");
while((line = myFile.readLine()) != null){
myTokens = new StringTokenizer(line,",");
dates = new String[myTokens.countTokens()];
int i=0;
while (myTokens.hasMoreTokens()) {
dates[i]=myTokens.nextToken();
i++;
}
// prints any items that are not 8 chars long
for (int j = 0; j < dates.length; j++){
if (dates[j].length() < 8){
System.out.println(dates[j]);
}
}
// I changed the date += String.valueof.dates[i] + "/n"
// to System.out.println
for (int n = 0; n < dates.length; n++){
if (dates[n].length() == 8){
System.out.println(dates[n]);
}
}
}
return date;
}
// I changed the datesort += String.valueof.dates[i] + "/n"
// to System.out.println
public String Sorted(String datesort){
selectionSort(dates, dates.length);
for (int i = 0; i < dates.length; i++){
if (dates[i].length() == 8){
System.out.println(dates[i]);
}
}
return datesort;
}
private static void selectionSort(String array[], int length) {
for ( int i = 0; i < length - 1; i++ ) {
int indexLowest = i;
for ( int j = i + 1; j < length; j++ )
if ( array[j].compareTo(array[indexLowest]) < 0)
indexLowest = j;
if ( array[indexLowest] != array[i] ) {
String temp = array[indexLowest];
array[indexLowest] = array[i];
array[i] = temp;
}
}
}
}
The out of this program is :
hello
20161001
20080912
20131120
19980927
20020202
20120104
20120104
Yet it should be:
hello
20161001
20080912
20131120
19980927
20020202
20120104
19980927
20020202
20080912
20120104
20131120
20161001
thanks ahead of time, I apologize if I was unclear at all.

Swapping string position in Arraylist java

I have a sentence: Humpty Dumpty sat on a wall.
I want the strings to swap positions such that : Dumpty Humpty on sat wall a.
So the code that I wrote is following :
import java.util.*;
public class Swap{
public static void main(String []args) {
ArrayList<String> sentence = new ArrayList<String>();
sentence.add("Humpty");
sentence.add("Dumpty");
sentence.add("sat");
sentence.add("on");
sentence.add("a");
sentence.add("wall");
int size = sentence.size() ; // for finding size of array list
int numb ;
if(size%2 == 0) {
numb = 1;
}
else {
numb = 0;
}
ArrayList<String> newSentence = new ArrayList<String>();
if(numb == 1) {
for(int i = 0; i <= size ; i = i+2) {
String item = sentence.get(i);
newSentence.add(i+1, item);
}
for(int i = 1; i<=size ; i = i+2) {
String item2 = sentence.get(i);
newSentence.add(i-1, item2);
}
System.out.println(newSentence);
}
else {
System.out.println(sentence);
}
}
}
The code is compiling correct but when I run it, its giving an error.
What i understand of this is that I am adding strings to the array list leaving positions in between. Like adding at position 3 without filling position 2 first. How do I overcome this problem ?
You're correct about your problem - you're trying to insert an element into index 1 before inserting an element at all (at index 0), and you get an IndexOutOfBoundsException.
If you want to use your existing code to achieve this task, simply have just one loop as such:
if(numb == 1) {
for(int i = 0; i < size-1 ; i = i+2) {
String item = sentence.get(i+1);
newSentence.add(i, item);
item = sentence.get(i);
newSentence.add(i+1, item);
}
}
If you want to be a bit more sophisticated a use Java's built-in functions, you can use swap:
for(int i = 0; i < size-1 ; i = i+2) {
Collections.swap(sentence, i, i+1);
}
System.out.println(sentence);
You can initilize newSentence using:
ArrayList<String> newSentence = new ArrayList<String>(Collections.nCopies(size, ""));
This will let you access/skip any position in between 0 and size. So you can keep your rest of the code as it is.
just remember all index are being populated with empty String here.
That is because:
for(int i = 0; i <= size ; i = i+2) {
String item = sentence.get(i);
newSentence.add(i+1, item);//Here you will face java.lang.IndexOutOfBoundsException
}
for(int i = 1; i<=size ; i = i+2) {
String item2 = sentence.get(i);
newSentence.add(i-1, item2);//Here you will face java.lang.IndexOutOfBoundsException
}
instead of this, try following code:
if(numb == 1) {
for(int i = 0; i < size-1 ; i +=2) {
Collections.swap(sentence, i, i+1);
}
}

Java For Loop repeat if value is more

I am taking characters from a string and its values are added still I am getting a particular value.. suppose my value to get is 50 .. i need to take character each from a string and add its values
for example the value I need to get is 10
and value for letters a=1,b=2,c-3;
and the string is abca so its total value is 1+2+3+1 = 7
so 10 didn't reached so I need to add once agin from start like abca 7 + 1 + 2. So at the place of b we got the 10 value.. so the result is 2.
I know how to take the value for once but the second time calculation an dthird time I am not getting if anyone can help..pls help
The code so far I completed..
long currentValueFN = 0;
long value = 0;
char[] currentFN = new char[text.length()];
currentFN = text.toCharArray();
Long l = Long.parseLong(String.valueOf(currentAge));
for(int i=0; i<text.length(); i++)
{
currentValueFN += valueLetters( currentFN[i] );
if(currentValueFN >= l)
{
value = valueLetters( currentFN[i] );
}
}
return value;
long currentValueFN = 0;
long value = 0;
char[] currentFN = new char[text.length()];
currentFN = text.toCharArray();
Long l = Long.parseLong(String.valueOf(currentAge));
while(currentValueFN < l ) //check if current value is enough
{
for(int i=0; i<text.length(); i++)
{
currentValueFN += valueLetters( currentFN[i] );
if(currentValueFN >= l)
{
value = valueLetters( currentFN[i] );
break;
}
}
}
return value;
1) if there are enough characters in "text": will escape from for by break and then from while by expression;
2) if there aren't enough characters in "text": will finish for and start it again by while expression. until 1)
please forgive me if my answer is wrong.
1)I have taken a string variable called "variable" and converted it to character array called "character_array"(array name).
2)Then i converted the character array elements to its equivalent ascii code and it is stored in an integer array called "value_array"(array name).
3)Then i checked the condition that the givenvalue is less than the addedvalue.
public class Stack {
public static void main(String args[])
{
long addedvalue=0;
long requiredvalue=600;
String variable="ravi";
char characterarray[]=new char[variable.length()];
for(int i=0;i<variable.length();i++)
{
characterarray[i]=variable.charAt(i);
System.out.println(characterarray[i]);
}
int valuearray[]=new int[variable.length()];
for(int j=0;j<variable.length();j++)
{
valuearray[j]=(int)(variable.charAt(j));
System.out.println(valuearray[j]);
}
while(addedvalue<=requiredvalue)
{
for(int j=0;j<variable.length();j++)
{
valuearray[j]=(int)(variable.charAt(j));
if(addedvalue>=requiredvalue)
break;
addedvalue=addedvalue+valuearray[j];
System.out.println(j);
}
}
}
}
This should help you.
currentValueFN =0;
a=0;
while(currentValueFN !=l){
a=valueLetters( currentFN[i] );
currentValueFN +=a;
if(currentValueFN >= l)
{
value = a;
break;
}
}
return value;

Printing string array also prints null

When I am printing contents of a string array the output is printing 'null' as well. I am not sure what's wrong with this. Here is the output, what I expect is the output without 'null'
null(wa?>=0)nullnull*(wo?>=0)nullnull*(4*wa?+7*wo?>=50)nullnull*(d1=10)nullnull*((d2=1)+(k=2))nullnull
Thanks and appreciate your help. I would say my skill in Java in beginner level and I started two weeks back.
Here is the actual code:
String[] arrStr = new String[50];
int countStr = 0;
for (int i = 0; i < para.length; i++) {
if (para[i] == '(') {
count = count + 1;
}
if (para[i] == ')') {
count = count - 1;
}
if (count > 0) {
arrStr[countStr] = arrStr[countStr] + para[i];
} else {
if (para[i] == ')') {
arrStr[countStr] = arrStr[countStr] + para[i];
countStr += 1;
} else {
countStr += 1;
arrStr[countStr] = arrStr[countStr] + para[i];
// System.out.println(para[i]);
}
}
}
System.out.println(countStr);
for (int i = 0; i < countStr; i++) {
System.out.print(arrStr[i]);
}
Before this part, I am reading the following string from a word document:
(wa?>=0)AND(wo?>=0)AND(4*wa?+7*wo?>=50)AND(d1=10)AND((d2=1)+(k=2))
I think the problem may be due to the line:
arrStr[countStr] = arrStr[countStr] + para[i];
Since arrStr[countStr] is null initially and I add an element to it, it saves it as null+para[i]. Do you think it is possible?
Like when I try: System.out.println(arrStr[0]); I get the output as
null(wa?>=0)
System.out.println(null + "Bla");
prints nullBla. A null represented as String is "null". The issue here is that initially all your String[] is made of null. You need to initialize them first. Typically,
Arrays.fill(arrStr, "");
Should do.
If any element in arrStr is null while printing, it will print that faithfully.
Without knowing specifics in your code, you can either ensure that no element in your array becomes null (ensure that the lengths match up and you're not skipping element in arrStr, or check for null before printing the element.
You don't initialize the values of the arrStr array, you just allocate size for it, so each element of the array is null. When you assign a value to an element of the array, you concatenate its value (which is null) with the value of para[i].
You should initialize your array before using it:
String[] arrStr = new String[50];
for (int i = 0; i < arrStr.length; i++) {
arrStr[i] = "";
}

Categories