Read and divide multiple lines from Stdin - java

I am trying to read in two lines of input from stdin, and copy the items of the first line into one array, and the items of the second line into another array. The items in each line have spaces between them, which I use to differentiate between the items. An example of the input would be:
1 2 3
4 5
At the moment 12345 is stored in one array but I want the result to be this:
arr1 = [1, 2, 3];
arr2 = [4, 5];
How would I do this?
import java.util.*;
public class Tester {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter lines:");
while(input.hasNext()) {
String s = input.nextLine();
String[] strArray = s.split(" ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
System.out.print(intArray[i]);
}
}
}

You should extract the parsing of a single line to a separate method:
private static int[] parseInts(String s) {
String[] strArray = s.split(" ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
After that, the code in main looks simpler:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter lines:");
int[] line1Numbers = parseInts(input.nextLine());
int[] line2Numbers = parseInts(input.nextLine());
// For the remaining lines:
while(input.hasNext()) {
String line = input.nextLine();
int[] numbers = parseInts(line);
for(int i = 0; i < strArray.length; i++) {
System.out.print(intArray[i]);
}
}
}

Related

Problems with iterated nextLine function

I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);

Taking a list of integers and displaying them in reverse using arrays [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
If my input is 1 2 3 the output is also coming out as 1 2 3, how do I make these numbers to display 3 2 1?
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
int[] nums = new int[entries.length];
for(int i = 0; i < entries.length; i++){
nums[i] = Integer.parseInt(entries[i]);
}
for(int i = 0; i < entries.length; i++){
System.out.println(nums[i]);
}
}
}
If you want to store numbers in reverse order:
for(int i = 0; i < entries.length; i++)
{
nums[i] = Integer.parseInt(entries[entries.length-i-1]);
}
If you want to just display numbers in reverse order(they'll remain same order in list:
for(int i = entries.length-1; i >= 0; i--)
{
System.out.println(nums[i]);
}
Try below code:
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
for(int i = entries.length-1; i >= 0; i--)
{
System.out.print(Integer.parseInt(entries[i])+ " ");
}
}
If you want Java 8 version, here is the code
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split("\\s");
List<Integer> integers = Arrays.stream(entries)
.map(Integer::valueOf)
.collect(Collectors.toList());
Collections.reverse(integers);
integers.forEach(integer -> System.out.print(String.format("%d ", integer)));
\\s indicates 'white space' and I suggest you to close Scanner at the end.
You could loop through your entries array backwards. This would involve starting int i at the length of entries minus 1 (as that is your last index in your array - ie your last number). It would also require that you keep looping while i >= 0. Lastly, instead of incrementing your i variable, you need to decrement it. This way your counter i will go from the end of your loop to the start of your array (eg: if you enter "1 2 3", i will go from indexes: 2, 1, 0)
See example below:
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
int[] nums = new int[entries.length];
for(int i = 0; i < entries.length; i++) {
nums[i] = Integer.parseInt(entries[i]);
}
for(int i = entries.length-1; i >= 0; i--) {
System.out.println(nums[i]);
}
}

when I input 4 abcd bcda cdab dabc,I want the result 1,but it turn out to be 4,I don't know why?

when I input
4
abcd
bcda
cdab
dabc
I want the result 1, but it turn out to be 4, I don't know why?
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
String[] strArr = new String[N];
for (int i = 0; i < N; i++) {
strArr[i] = sc.nextLine();
}
System.out.println(fun(strArr));
}
public static int fun(String[] arr) {
TreeSet<String> treeSet = new TreeSet<>();
for (int i = 0; i < arr.length; i++) {
char[] chars = arr[i].toCharArray();
Arrays.sort(chars);
treeSet.add(chars.toString());
}
return treeSet.size();
}
}
Here is your working code:
/**
* #param args
*/
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
String[] strArr = new String[N];
// StringBuffer sb = new StringBuffer();
for (int i = 0; i < N; i++) {
strArr[i] = sc.nextLine();
}
System.out.println(fun(strArr));
}
public static int fun(final String[] arr) {
TreeSet<String> set = new TreeSet<>();
for (int i = 0; i < arr.length; i++) {
char[] chars = arr[i].toCharArray();
Arrays.sort(chars);
set.add(new String(chars));
}
return set.size();
}
The problem is as you can see the toString of chars delivers you the memory address representation. therefore you get 4 items as it is always a new instance of the same string.
You are using treeSet.add(chars.toString()); which actually refers to Object.toString() which formats the array as something like [C#39ed3c8d.
If you use:
treeSet.add(Arrays.toString(chars));
the strings will look like [a, b, c, d] which should then do what you want.

Changing input so in can take any length of string, problems with output

Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.

How do you populate an array with String input from a file?

Assume that i have 4 grades in testgrades.txt I don't know why this wont work.
public static void main(String[] args) throws FileNotFoundException {
File file1= new File("testgrades.txt");
int cnt = 4;
int[] grades = new int[cnt];
String line1;
for (int i=0; i<cnt; i++) {
Scanner inputFile2 = new Scanner(file1);
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
System.out.print(grades);
First of all, you should note that arrays in java hold fixed-size elements of the same type.
You can initialize them in one of two ways (not very sure if there are other ways).
//First method
int[] anArray = new int[10];
// Second method
int[] anArray = {1,2,3,4,5,6,7,8,9,10};
In either case, the array is of size 10 elements. Since you are fetching the data from the text file, I'll suggest you count number of lines into a variable and use that value to initialize the array. Then you can use a loop to fill the values this way:
// Assuming you have cnt as your total count of grades.
int[] grades = new int[cnt];
String line1;
for (int 1=0; i<cnt; i++) {
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
This is coming off my head so let me know if you face any problem.
You can do like this
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
File file= new File("testgrades.txt");
Scanner scan = new Scanner(file);
int arr[] = new int[100];
int i = 0;
do{
String line1 = scan.nextLine();
int grades2 = Integer.parseInt(line1);
arr[i++] = grades2;
}while(scan.hasNextLine());
for(int j = 0; j < i; j++){
System.out.println(arr[j]);
}
}

Categories

Resources