Scanner input values are not all being stored - java

I have a scanner which reads in strings as coordinate inputs. I have to convert these strings into integers and store them in an Arraylist of coordinates but the last values I input are not being stored in the arraylist.
I have tried using the startEndLineScan.nextLine(); outside the for-loop but still no change I have also tried using a while loop instead of a for loop when storing and parsing the strings but I get the same results.
ArrayList<Integer> convertedCoords = new ArrayList<Integer>();
String samplePointsCoords[];
Scanner startEndLineScan = new Scanner(System.in);
int count = 1;
while (startEndLineScan.hasNextLine()) {
startEndPointsInputs = startEndLineScan.nextLine();
samplePointsCoords = startEndPointsInputs.split(",");
if (count < 2) {
for (int i = 0; i < samplePointsCoords.length; ++i) {
convertedCoords.add(Integer.parseInt(samplePointsCoords[i]));
}
count++;
} else {
break;
}
}
System.out.print("Points: " + convertedCoords)
Input:
1,2
3,4
Expected results:
Points: [1,2,3,4]
Actual Results
Points: [1,2]

ArrayList<Integer> convertedCoords = new ArrayList<Integer>();
String samplePointsCoords[];
Scanner startEndLineScan = new Scanner(System.in);
int count;
while (startEndLineScan.hasNextLine()) {
count = 1;
startEndPointsInputs = startEndLineScan.nextLine();
samplePointsCoords = startEndPointsInputs.split(",");
if (count < 2) {
for (int i = 0; i < samplePointsCoords.length; ++i) {
convertedCoords.add(Integer.parseInt(samplePointsCoords[i]));
}
count++;
} else {
break;
}
}
System.out.print("Points: " + convertedCoords)
Notice int count; is declared and reinitialized at the start of every loop
This will fix your code but you should really try to understand what you are writing! cheers.

Related

Compare arraylists for non identical elements

Hello there I am being confused in comparing two array lists, one of my array list is as:
private ArrayList<String> members = new ArrayList<>();
members.add("member123keyxyzmember123 number");
members.add("member456keyxyzmember456 number");
members.add("member789keyxyzmember789 number");
members.add("member2233keyxyzmember2233 number");
members.add("member1122keyxyzmember1122 number");
The second arraylist is as:
private ArrayList<String> syncMembers = new ArrayList<>();
syncMembers.add("member123keyxyz123statuskeyxyz123photokeyxyzmember123 number");
syncMembers.add("member456keyxyz456statuskeyxyz456photokeyxyzmember456 number");
The problem is that I am comparing both so that they give me the numbers that are in members list and are not in syncMembers list!
That is the out put should be:
member789 number
member2233 number
member1122 number
only!
What I have been trying is:
for (int i = 0; i < members.size(); i++) {
String stringFromMembersList = members.get(i);
String[] memberParts = stringFromMembersList.split("keyxyz");
String memberNumber = memberParts[1];
//Log.e("hgax", "sync:::" + memberNumber);
for (int j = 0; j < syncMembers.size(); j++) {
String stringFromSyncList = syncMembers.get(j);
String[] syncParts = stringFromSyncList.split("keyxyz");
String n = syncParts[3];
if (memberNumber.equals(n)) {
//Log.e("hgax", "hee:::" + n);
break;
} else {
Log.e("hgax", "ssshee:::" + memberNumber);
}
}
}
The output I am getting is:
member456 number
member789 number
member789 number
member2233 number
member2233 number
member2233 number
member1122 number
member1122 number
member1122 number
member1122 number
I am bit confuse what is happeing to me and What i have been doing wrong? Can somebody please tell what blunder I am doing Thanks in advance
Try to think about what you need to check to reach your goal. In order to determine that a member in the list members does not exist in syncMembers you have to check the entirety of the syncMembers list for that member. Since the lists are not identical (as your question states), you cannot use Collection.contains(Object o).
This should achieve your goal:
// We need this initial check as if syncMembers is empty it'll display all members
// And why bother to do this if syncMembers is empty anyway!
if (!syncMembers.isEmpty()) {
for (String member : members) {
String memberNo = member.split("keyxyz")[1];
int i = 0;
boolean found = false;
while (!found && i < syncMembers.size()) {
// Iterate over syncMembers until a match if found
// or we have exhausted the list
found = syncMembers.get(i).split("keyxyz")[3].equals(memberNo);
i++;
}
if (!found) {
// Display only if not found
System.out.println(memberNo);
}
}
}
Edit: updated answer to include the original mixed values in the arrayList
ArrayList<String> membersList = new ArrayList<>();
ArrayList<String> syncMembersList = new ArrayList<>();
for (int i = 0; i < members.size(); i++) {
String s = members.get(i).substring(members.get(i).lastIndexOf("member"));
membersList.add(s);
}
for (int j = 0; j < syncMembers.size(); j++) {
String s = syncMembers.get(j).substring(syncMembers.get(j).lastIndexOf("member"));
syncMembersList.add(s);
}
for (int i = 0; i < membersList.size(); i++) {
if (!syncMembersList.contains(membersList.get(i))) {
System.out.println(membersList.get(i));
}
}
This will print the output you require.

Java - NumberFormatException when using .parseInt(String)

I am trying to run a loop to see if an int is sorted. however the int has to be converted from a string. here is my code.
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
when I run it, I get an error :
Exception in thread "main" java.lang.NumberFormatException: null
0149 at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
why does Integer.parseInt() not work
Your problem is that digits[a+1] hasn't been defined yet. I see that on line 2 you have
digits[a] = Character.toString(sq.charAt(a));
and you're iterating over a in a for loop, so I daresay that digits[a+1] hasn't been assigned yet.
UPDATE 1
Check out this solution, it shows how to properly catch that exception and how to avoid it:
Java: Good way to encapsulate Integer.parseInt()
UPDATE 2
I decided to add a fixed version of your code:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1 || a == 0){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
While I don't know the utility of your code, but this implementation might be simpler:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
long sq = i*i;
if(sq > 9){
String[] digits = sq.toString().split("");
//Notice that I start at index 1, so I can do [a-1] safely
for(int a = 1; a < digits.length; a++){
if(Integer.parseInt(digits [a-1]) < Integer.parseInt(digits[a])){
System.out.print(sq);
//I guess we don't want a number like 169 (13*13) to be displayed twice, so:
break;
}
}
} else {
System.out.print(sq);
}
}
}

sub arraylist's size isn't correct

After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());

Convert array elements from string to an integer

I'm trying to count up the values stored in an array, here is my code:
public void printScores()
{
String sep = ":";
File inputfile = new File ("P:/SD/Assignment1/fbScores.txt");
String [] stringArr;
String line = "";
try {
Scanner filescan = new Scanner(inputfile);
while(filescan.hasNext())
{
line = filescan.nextLine();
stringArr = line.split(sep);
if(stringArr.length == 4)
{
System.out.println(stringArr[0]+"\t [" +stringArr[2]+"]\t|" + stringArr[1]+"\t["+ stringArr[3]+" ]\n");
}
else
{
throw new IllegalArgumentException("String " + line + " does not contain " + sep);
}
}
filescan.close();
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
public void totalGoals()
{
int count;
for (int i = 0; i<stringArr.length; i++)
{
//int num[i] = Integer.parseInt(stringArr);
}
}
}
Basically I only want to add the numbers up that are stored in [2] and [3], my totalGoals method at the bottom is where I started, but can't figure out how to change from a string to an integer, any help would be much appreciated!
UPDATE:
public void totalGoals()
{
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
You want to parse each string individually - you seem to be trying to do the whole array
int[] num = new int[stringArr.length]; //don't forget to declare your num[] array
for (int i = 0; i<stringArr.length; i++)
{
num[i] = Integer.parseInt(stringArr[i]); // stringArr[i] instead of stringArr
}
Note what this code is actually doing when you break it out of the for loop format.
int[] num = new int[4];
num[0] = Integer.parseInt(stringArr[0]); //the for loop is starting at 0 and stopping
num[1] = Integer.parseInt(stringArr[1]); //when it hits 4
num[2] = Integer.parseInt(stringArr[2]);
num[3] = Integer.parseInt(stringArr[3]);
In truth, you only need 2 and 3.. and all you need to do is add them together. You already have a count variable you could use instead of num
So lets say you only want to loop through 2 and 3... look at the for loop
for (int i = 0; i < stringArr.length; i++)
int i = 0 //your loop is starting at 0
i < stringArr.length; //its ending when i is the array's length (should be 4 judging by your other code)
i++ // i increases by 1 at the end of each time through
So if 0 and 1 are useless, try using int i = 2
You have a count variable. Maybe it should start at 0.. and rather than setting the num variable, you could add the value to your count variable.
About your method.. By itself it should be working.
I'm also not sure which line is line 73
If it is the first line: int[] num = new int[stringArr.length]; Then either your stringArr doesn't exist (for this method) or your stringArr isn't initialized (again, for this method)
Looking at the code you've shown me, I'm guessing the problem is on that first line.
public void printScores() {
//other code
String[] stringArr;
//other code
}
public void totalGoals() {
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
Done simply like this, you wouldn't even be able to compile. stringArr would not exist for totalGoals. The two methods are separate and cannot "see" each other's variables.
If you have your code like below - then you are declaring stringArr twice and you have two separate variables named the same thing!
{
String[] stringArr; //This is what totalGoals would be using - it is never assigned
public void printScores() {
String[] stringArr; //This one is used and assigned within printScores
//but totalGoals cannot see/use it
}
public void totalGoals() {
}
}
Use Integer.parseInt(String s) or Integer.parseInt(String s, int radix) to convert your Strings to Integers or primitive ints.
For instance:
try {
String s = "42";
int i = Integer.parseInt(s);
}
catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
You can also use Scanner.nextInt if that suits your context better.
Use integer.parseint to parse string to int
if(stringArr.length == 4)
{
for(int i=0;i<stringArr.length;i++)
{
int c = Integer.parseInt(stringArr[2])+ Integer.parseInt(stringArr[3]);
}
}

Java String Bubble Sorting

I need help sorting this array in alphabetical order using the bubble sort algorithm.
My code is:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
The code compiles, but it does not sort alphabetical. Please help me.
You have three errors in your code.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1 not i < t1.length -1. You subtract t because you do not want to loop through the whole array again, only the first part of it.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
The other error in this line is that in the compareTo parameter you put 1 + 1 it actually should be just i, because you want one less than the object it is comparing to.
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
please change
String[] t1 = s1.split(", ");
to
String[] t1 = s1.split("");
This will solve the issue.

Categories