Problems with iterated nextLine function - java

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

Related

Alternative way to get the string input from the user [duplicate]

This question already has answers here:
Why does input.nextint method have a \n as a leftover?
(2 answers)
What does java.lang.ArrayIndexOutOfBoundsException mean? [duplicate]
(7 answers)
Closed 2 years ago.
I have implemented the following code which takes these values as input:-
3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1
But for taking string input I tried nextLine() but it is not taking input in that case.If I use next() then it treats CLICK and 1 as two different strings and so I am getting ArrayIndexOutOfBoundsException as I am splitting the string and parsing it to int. What is the alternative to handling such inputs?
import java.util.*;
public class TweetClose {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int open = 0;
int a[] = new int[50];
for (int i = 1; i <= n; i++) {
a[i] = 0;
}
for (int i = 0; i < k; i++) {
String s = sc.nextLine();
if (s.equals("CLOSEALL")) {
open = 0;
for (int j = 1; j <= n; j++) {
a[j] = 0;
}
} else {
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
if (a[y] != 1) {
a[y] = 1;
open++;
}
}
System.out.println(open);
}
sc.close();
}
}
sc.nextInt() does not scan the carriage return symbol. You need to make sure to scan that before trying to parse the next input.
e.g.:
import java.util.*;
public class TweetClose {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int k = sc.nextInt();
sc.nextLine();
int open = 0;
int[] a = new int[50];
for (int i = 1; i <= n; i++) {
a[i] = 0;
}
for (int i = 0; i < k; i++) {
String s = sc.nextLine();
if (s.equals("CLOSEALL")) {
open = 0;
for (int j = 1; j <= n; j++) {
a[j] = 0;
}
} else {
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
if (a[y] != 1) {
a[y] = 1;
open++;
}
}
System.out.println(open);
}
sc.close();
}
}
The problem caused by using nextLine(). You should use next() instead because you want to process the next token.
After processing all tokens, the final line-break of the current line is still in memory. nextLine() returns that line break "\n". Then you process it:
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
The split function returns an array with only one element (the "\n"), therefore you cannot parse st[1]. There is no such element, only st[0] exists.
It will work with next() instead of nextLine() because next() skips over the line break and proceeds with the next token of the next line.
This is a very common mistake because there is no nextString() function.

Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

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 to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.
try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}
Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

Categories

Resources