Java String Bubble Sorting - java

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.

Related

Java Stdin Cannot convert from String[] to String, but inputs are String?

I am doing a programming assignment that takes all of its input from stdin. The first input is an int n to tell you how many strings will follow, and the next n inputs are strings of varying lengths. The goal is to find the longest string(s) and print them.
I thought this was easy, but for the life of me, I cannot get the stdin to work with me. The eclipse arguments entered are (separated by enter):
3
a2
b3c
7
Yet I run the program, and it tells me it cannot convert from String[] to String. I do not understand how any of the above are String[]. The code is below:
import java.util.Scanner;
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
Scanner sc = new Scanner(System.in);
for (int i=0; i < size; i++) {
str[i] = sc.nextLine().split(" "); // The error
//str[i] = sc.next(); This line and the line below throw
//str[i] = sc.nextLine(); no errors, but also gives no output.
}
String[] longest = new String[size];
String[] temp = new String[size];
longest[0] = str[0];
int numToBeat = str[0].length();
int k = 0;
for (int i=0; i < size; i++) {
if (str[i].length() > numToBeat) {
numToBeat = str[i].length();
k = 0;
longest = temp;
longest[k] = str[i];
k++;
}
else if (str[i].length() == numToBeat) {
longest[k] = str[i];
}
}
System.out.println("The longest input strings are:");
for (int i=0; i < k; i++) {
System.out.println(longest[i]);
}
sc.close();
}
}
Tried:
Changing str[i] = sc.nextLine().split(" "); to its other variations in the code
Changing input values
Googling stdin for the last hour trying to find any documentation that helps me
If you are using eclipse arguments separated by enter then your logic is wrong:
according to your logic get 1st element from the eclipse argument like args[0]
another Input is taken from the console.
if you need to take all elements from the eclipse argument follow the below code:
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
int length=0;
String loggestString="";
for (int i=1; i < size; i++) {
str[i] = args[i];
int strLen = str[i].length();
if(strLen>length) {
length=strLen;
loggestString=str[i];
}
}
System.out.println(loggestString);
}
}

Keep getting run Time error in Kattis. Using Java as a language

Hello I've been getting this error in Kattis, 'Run time error' while all my test cases are correct in my own machine. Tested everything but as soon as i run this in kattis i get a run time error. Can you guys help me figure this out? Ive been debugging for hours but i am struggling.
https://open.kattis.com/problems/throwns?editsubmit=9372235 :Link of the problem
import java.util.*;
import java.io.*;
public class GOT{
public static void main(String[] args)throws IOException{
BufferedReader bi = new BufferedReader(new I
nputStreamReader(System.in));
int[] parseLine1 = new int[2];
String[] strLine1;
strLine1 = bi.readLine().split(" ");
//Parsing of 1st line of inputs i.e. N and K
for (int i = 0; i < strLine1.length; i++) {
parseLine1[i] = Integer.parseInt(strLine1[i]);
}
//init of Kids array
int[] nKids = new int[parseLine1[0]];
String[] commands = new String[parseLine1[1]];
int i;
for(i = 0; i < nKids.length; i++){
nKids[i] = i;
}
//parsing of 2nd line which are the commands
String strLine2;
String[] nCommands;
Scanner sc = new Scanner(System.in);
strLine2 = sc.nextLine();
nCommands = strLine2.split(" ");
int holder=0;
ArrayList<Integer> tracker = new ArrayList<Integer>();
int exit;
int throwns;
int undoCtr=0;
for(i = 0; i<nCommands.length; i++){
if(nCommands[i].equals("undo")){
nCommands[i] = nCommands[i].replaceAll("undo","101");
}
}
exit = nCommands.length;
i = 0;
while(exit != 0){
//System.out.println(Integer.parseInt(nCommands[i]));
if(Integer.parseInt(nCommands[i]) > 0){
for(int k = 0; k< Integer.parseInt(nCommands[i]); k++){
holder++;
if(holder==nKids.length){
holder = 0;
}
}
}if(Integer.parseInt(nCommands[i]) < 0){
for(int k = Integer.parseInt(nCommands[i]); k<0 ; k++){
holder--;
if(holder==0){
holder = nKids.length;
}
}
}else if(Integer.parseInt(nCommands[i]) == 101){
i++;
undoCtr = Integer.parseInt(nCommands[i]);
while(undoCtr!=0){
tracker.remove(tracker.size()-1);
undoCtr--;
}
exit--;
}
tracker.add(holder);
exit--;
i++;
}
System.out.println(tracker.get(0));
}`
}`
Your approach is too complex for a 2.8 difficulty problem. If you find yourself writing more than 25 lines of code, it's usually time to take a step back and re-think your approach.
Here's the algorithm that worked for me:
Make a list of "final" throw commands, initially empty.
Loop over the input tokens and analyze each command:
If a command is a number, append to the command list.
If a command is an undo n, pop the command list n times.
Now sum the commands in the list and print the mod of this sum, taking care to keep the mod positive.
Here's the spoiler:
public class Throwns {
public static void main(String[] args) {
var sc = new java.util.Scanner(System.in);
int n = Integer.parseInt(sc.nextLine().split(" ")[0]);
var line = sc.nextLine().split(" ");
var commands = new java.util.ArrayList<Integer>();
int sum = 0;
for (int i = 0; i < line.length; i++) {
if (line[i].matches("^-?\\d+$")) {
commands.add(Integer.parseInt(line[i]));
continue;
}
for (int j = Integer.parseInt(line[++i]); j > 0; j--) {
commands.remove(commands.size() - 1);
}
}
for (int c : commands) {
sum += c;
}
System.out.println(Math.floorMod(sum, n));
}
}

Scanner input values are not all being stored

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.

Java: Possible to use a single for-loop instead of two?

My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for (int arr_i = 0; arr_i < n; arr_i++) {
arr[arr_i] = in.nextInt();
}
for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
System.out.print(arr[reverse_i]);
if (reverse_i != 0) {
System.out.print(" ");
}
}
}
An example input:
4
1 2 3 4
Expected output:
4 3 2 1
Use a StringBuilder and always insert at 0 index.
See: Oracle » JavaDocs » 1.7 » java.lang.StringBuilder.insert(int, int)
StringBuilder bld = new StringBuilder();
for (int arr_i = 0; arr_i < n; arr_i++) {
int i = in.nextInt();
bld.insert(0, i);
}
System.out.println(bld.toString());
The simplest approach I found is to use String Builder here:
Scanner in = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (in.hasNext()) {
stringBuilder.append(in.next());
if(in.hasNext()) {
stringBuilder.append(" ");
}
}
System.out.print(stringBuilder.reverse());
First, you might reverse your elements as you insert them in the array. Then, assuming you are using Java 8+, you could use an IntStream instead of a loop and print with a basic Collector. Like,
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
IntStream.range(0, n).forEachOrdered(i -> arr[n - i - 1] = in.nextInt());
System.out.println(IntStream.of(arr).mapToObj(String::valueOf)
.collect(Collectors.joining(" ")));
I am not sure about the requirements of your request, but you do not necessarily have to use an array for this. You can concatenate the inputs into a String in reverse order like so.
public static void main(String[] args) {
System in = new Scanner(System.in);
int n = in.nextInt();
String allNumbers = "";
for (int i = 0; i < n; i++) {
int current = in.nextInt();
allNumbers = current + " " + allNumbers;
}
if(allNumbers != ""){
allNumbers = allNumbers.substring(0,allNumbers.length()-1);
}
System.out.println(allNumbers);
}
Java has inbuilt String method for the same. If your input is a String, you can use the below-
String s1 = new String("new");
String s2 = s1.reverse();
System.out.println(s2) // wen

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);
}
}
}

Categories