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

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

Related

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

Reading multiple lines output

I am reading multiple lines from the command line looking like this:
10 12
71293781758123 72784
1 12345677654321
Then I calculate stuff with the data of each line and output exactly the same amount of lines.
Unfortunately, I never get more than one line output in the end, namely the result of the last one.
The input function looks like that:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
String line = input.nextLine();
String[] lines = line.split(" ");
System.out.println(fct(lines[0], lines[1]));
}
input.close();
}
fct outputs a String.
Is there something weird happening I am not aware of?
Edit: I have added fct,since this could also be the problem:
public static String fct(String stringA, String stringB) {
int [] a = new int[stringA.length()];
int [] b = new int[stringB.length()];
for(int i=0; i< stringA.length(); i++) {
a[i] = stringA.charAt(i) - '0';
}
for(int i=0; i< stringB.length(); i++) {
b[i] = stringB.charAt(i) - '0';
}
if(a.length < b.length) {
int[] c = a.clone();
a = b.clone();
b = c.clone();
}
Stack<Integer> s = new Stack<Integer>();
int carry = 0;
int b_ind = b.length -1;
for(int i=a.length-1; i>=0; i--) {
if(b_ind >= 0) {
int diff = a[i] - b[b_ind] - carry;
if(diff < 0) {
carry = 1;
diff = 10 + diff;
} else {
carry = 0;
}
s.push(diff);
} else {
if(carry==0) {
s.push(a[i]);
} else {
s.push(a[i]-carry);
carry = 0;
}
}
b_ind -= 1;
}
String all = "";
while(!s.empty()) {
all = all + s.pop();
}
return all.replaceFirst("^0+(?!$)", "").trim();
}
The output would then be:
2
71293781685339
12345677654320
Being directly on the console on the line after the input finished.
Add one line break after last input line 1 12345677654321. Otherwise program won't read last line till you press enter(return) key.
If you want output on console like this:
10 12
71293781758123 72784
1 12345677654321
98
71293781685339
12345677654320
But you are getting this:
10 12
71293781758123 72784
1 1234567765432198
71293781685339
Notice, 98 is getting appended to last input line. And the second output is on the next line. You actually have two outputs.
And the third input has not been read by the program because third input line doesn't end in new line. If you press Enter key here the program will process the third input.
You need to make sure that there is a new line character after last input line before pasting entire input in to console.
Just a sidenote:
I would use java.math.BigInteger in this context (math with big integers).
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
try (var scanner = new Scanner(System.in)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lines = line.split(" ");
System.out.println(fct(lines[0], lines[1]));
}
}
}
public static String fct(String numberA, String numberB) {
var a = new BigInteger(numberA);
var b = new BigInteger(numberB);
return a.subtract(b).abs().toString();
}
}

Input from the console in java

I know this is a basic question but I have been trying hard to find Which method I can use if I have to take 2 {123,456} as the input from console where 2 is the number of inputs to the array and {123,456} are inputs to the array. Should I be using Regex for this since it has { symbols or can it be done by scanner alone??
You can read the array part as String and then strip the curly braces using substring. Convert the String to int and store into an array.
import java.util.Scanner;
public class ReadArray {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int count = read.nextInt();
String arrayLine = read.next();
int array[] = new int[count];
String elements[] = arrayLine.split(",");
elements[0] = elements[0].substring(1);
elements[count-1] = elements[count-1].substring(0, elements[count-1].length()-1);
for (int i=0; i<count; i++) {
array[i] = Integer.parseInt(elements[i]);
}
for (int i : array) {
System.out.println(i);
}
}
}
Input :
2 {123,456}
Output :
123
456
Assuming you have read the input as a string, you can do the following:
String[] inputs = input.split(" ");
int arrayLength = Integer.parseInt(inputs[0]);
String inputStringData = inputs[1].substring(1, inputs[1].length());
String[] arrayElements = inputStringData.split(",");
int[] array = new int[arrayLength];
for(int i=0; i<array.length; i++) {
array[i] = Integer.parseInt(arrayElements[i]);
}

Reading in information into multiple arrays

The purpose of this program is to take information from a file about a music collection and turn it into three arrays.
>4
>141 Pure Heroine:Lorde
>171 Lights Out:Ingrid Michaelson
>270 Unorthodox Jukebox :Bruno Mars
>190 Head Or Heart:Christina Perri
In the file, the 4 stands for how long the arrays will be, the numbers are one array, the album titles another, and the artist names are the final array. The arrays for the titles and artist names are separated by the colon. While I can create the array for the numbers, what is giving me trouble is how to create the separate arrays for name and titles. I understand that I have to convert it into a sting and use the colon as a delimiter but I'm unsure as to how.
import java.util.*;
import java.io.*;
public class tunes {
public static void main(String[] args) throws FileNotFoundException {
int size; //Determines the size of the arrays
Scanner input = new Scanner(new File("music.txt"));
size = input.nextInt();
int[] time = new int[size];
for (int i = 0; i < time.length; i++) { // Creates an array for the numbers
time[i] = input.nextInt();
input.nextLine();
}
String[] artist = new String[size];
for (int i = 0; i <artist.length; i++) {
while (input.hasNextLine()){
}
}
System.out.println();
System.out.println("TOTAL TIME\t\t\t\t" + calcTotalTime(time));
System.out.println();
System.out.println();
System.out.println("LONGEST TRACK");
System.out.println("-------------");
System.out.println();
System.out.println();
System.out.println("SHORTEST TRACK");
System.out.println("--------------");
}
public static void printTable(int[] time, String[] artist, String[] title) {
System.out.println("TITLE\t\t\t" + "ARTIST\t\t\t " + "TIME");
System.out.println("-----\t\t\t" + "------\t\t\t " + "----");
for (int i = 0; i < time.length; i++) {
System.out.println(title[i] + "\t" + artist[i] + "\t" + time[i]);
}
}
public static int calcTotalTime(int[] time) {
int sum = 0;
for (int i = 0; i < time.length; i++) {
sum = sum + time[i];
}
return sum;
}
public static int findLongest(int[] time) {
int longest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] > time[longest]) {
longest = i;
}
}
return longest;
}
public static int findShortest(int[] time) {
int shortest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] < time[shortest]) {
shortest = i;
}
}
return shortest;
}
}
An example of how the output would look like would be
>Pure Heroine Lorde 141
>Lights Out Ingrid Michaelson 171
>Unorthodox Jukebox Bruno Mars 270
>Head or Heart Christina Perri 190
You can use String.split(":") on your text to split the artist/title Strings into String[] arrays.
For instance:
System.out.println(Arrays.toString("Head Or Heart:Christina Perri".split(":")));
Output
[Head Or Heart, Christina Perri]
Use the String split() method to save the pieces into a new array. The split() method takes a regular expression - see this question about how to use it. The colon is not a special character in a RegExp and therefore does not need to be escaped.
Allocate all the arrays first after reading the length of the arrays, then parse each line in one go using split to tokenize the artist-title part of the line.
size = input.nextInt();
int[] time = new int[size];
String[] artist = new String[size];
String[] title = new String[size];
for (int i = 0; i < time.length; i++) {
time[i] = input.nextInt();
String[] parts = input.next().split( ":" );
artist[i] = parts[0];
title[i] = parts[1];
}

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