This question already has answers here:
Scanner skipping every second line from file [duplicate]
(5 answers)
Closed 4 years ago.
My program prints all the data on the line, but only prints every other line. I know that it has something to do with the "nextLine", but I cannot find whats causing the problem.
import java.io.*;
import java.util.*;
public class hw2
{
public static void main (String[] args) throws Exception
{
String carrier;
int flights;
int lateflights;
int ratio;
String[][] flightData= new String [221][3];
String[] temp;
File file = new File ("delayed.csv");
Scanner csvScan = new Scanner(file);
int c = 0;
while ((csvScan.nextLine()) != null){
String s = csvScan.nextLine();
temp = s.split(",");
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
flightData[c][0] = temp[1];
flightData[c][1] = temp[6];
flightData[c][2] = temp[7];
c = c+1;
}
}
}
Consider this approach (see doc here):
Scanner csvScan = new Scanner(file);
while (csvScan.hasNextLine()) {
String s = csvScan.nextLine();
// for testing
System.out.println(s);
// ... rest of code
}
Related
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
I am just a beginner and do not know how to reverse text that I write on input so it is reversed on output. I wrote something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] pole = {s};
for (int i = pole.length; i >= 0; i--) {
System.out.print(pole[i]);
} // TODO code application logic here
}
}
but it is not working and I cannot figure out why.
Welcome to SO and java world.
As I understand the problem is not only reversing a String. The problem is also you do not know about Strings and arrays.
Let's see your code line by line;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read a String
String s = sc.nextLine();
// Put String into an array
String[] pole = { s };
// pole's length is 1, because pole has only one String
for (int i = pole.length; i > 0; i--) {
// pole[i-1] is the input String
// System.out.print(pole[i]); // pole[i] get java.lang.ArrayIndexOutOfBoundsException
System.out.print(pole[i - 1]); // this will print input string not reverse
}
// To iterate over a String
for (int i = s.length() - 1; i >= 0; i--) { // iterate over String chars
System.out.print(s.charAt(i)); //this will print reverse String.
}
}
Also as given on comments, Java have ready methods to reverse a String. Like;
new StringBuilder(s).reverse().toString()
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
public static void main (String args[]) {
Scanner io = new Scanner(System.in);
int a = io.nextInt();
io.nextLine();
for(int i = 0; i < a; i++ ) {
String input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[] = new int[input.length()];
int q = 0;
for (String par : splitArr) {
System.out.println(par);
p[q++] = Integer.parseInt(par);
System.out.println(p);
}
Sort(p);
}
}
The input: 2 121213
Output: 121213 [I#1f96302
The last line shows the array stored in p[]. That is incorrect. Help someone!
Your print line is incorrect, your print line should be:
System.out.println(Arrays.toString(p));
You also increment q in a wrong way, your increment code should be like:
p[q] = Integer.parseInt(par);
q++;
System.out.println(p);
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
Getting NumberFormatException. What am I doing wrong here ?
I'm trying to read an array of integers separated by spaces.
Is there any other better way to do the same ? I did a lot of research and most people said that split() is better than StringTokenizer and BufferedReader.
public static void main (String args[])
{
#SuppressWarnings("resource")
Scanner io = new Scanner(System.in);
int a=io.nextInt();
String input;
for(int i=0; i<a; i++)
{
input = io.nextLine();
int x= input.length();
String[] splitArr = input.split("\\s+");
int p[]= new int[x];
int q=0;
for (String par : splitArr) {
p[q++] = Integer.parseInt(par);}
System.out.println(p);
}
}
}
Updated Code, working now:
public static void main (String args[])
{
#SuppressWarnings("resource")
Scanner io = new Scanner(System.in);
int a=io.nextInt();
io.nextLine();
String input;
for(int i=0; i<a; i++)
{
int x= io.nextInt(); //size of array
io.nextLine();
input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[]= new int[x];
int q=0;
for (String par : splitArr) {
p[q++] = Integer.parseInt(par);}
for(int m=0; m<x; m++)
System.out.print(p[m]+" ");
}
}
}
Do a io.nextLine(); (without storing it anywhere) after int a=io.nextInt(); (just before any string input that you'd want to take).
Something like
Scanner io = new Scanner(System.in);
int a=io.nextInt();
io.nextLine();
String input;
Loop through your array to get the values properly; not System.out.prinltn(p);
Try doing something like this
while(io.hasNext()){
try{
somevar = io.nextInt()
}
catch (NumberFormatException e){
//just pass through this non int value or do some error handlin
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am trying to figure out how to read a list of Strings in a text file and return the position of the word found. I'm not sure why this isn't working. Can someone tell me what I'm doing wrong? It returns -1 for each word and the words are definitely in there.
public class LinearSearch extends SearchAlgorithm
{
public int search(String[] words, String wordToFind) throws ItemNotFoundException {
for (int i = 0; i < words.length; i++) {
if (words[i] == wordToFind) {
return i;
}
else {
return -1;
}
}
return -1;
}
public final static String FILE_AND_PATH = "longwords.txt";
/*
* TODO: Be sure to change the FILE_AND_PATH to point to your local
* copy of longwords.txt or a FileNotFoundException will result
*/
//Note how we deal with Java's Catch-or-Declare rule here by declaring the exceptions we might throw
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/myName/Desktop/compsci/HOMEWORK/recursion/longwords.txt");
Scanner input = new Scanner(file);
int wordCount = 0;
ArrayList<String> theWords = new ArrayList<String>();
//read in words, count them
while(input.hasNext()) {
theWords.add( input.next() );
wordCount++;
}
//make a standard array from an ArrayList
String[] wordsToSearch = new String[theWords.size()];
theWords.toArray(wordsToSearch);
//start with the linear searches
tryLinearSearch(wordsToSearch, "DISCIPLINES");
tryLinearSearch(wordsToSearch, "TRANSURANIUM");
tryLinearSearch(wordsToSearch, "HEURISTICALLY");
tryLinearSearch(wordsToSearch, "FOO");
You can't compare Strings with words[i] == wordToFind. You have to use words[i].equals(wordToFind).
You also should remove the else block within the for loop.
Your loop is returning on the first iteration. Remove the else block.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am writing a code which reads the following input
3
Ruby
Diamond
Sapphire
Here is my program
import java.util.Scanner;
public class GemStones {
private int numOfStones;
private String[] gemArray;
public void solve() throws Exception{
Scanner in = new Scanner(System.in);
//Reading the integer
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
//reading the strings
for(int i=0;i<numOfStones;i++){
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
for(int i=0;i<numOfStones;i++){
System.out.println(gemArray[i]);
}
in.close();
}
public static void main(String[] args) throws Exception {
GemStones check = new GemStones();
check.solve();
}
}
I have a problem reading the strings following it. Whenever I try to read the strings it shows me error! please help me..
The following is the error I get in the console
3
Ruby
Diamond
Sapphire3Exception in thread "main"
java.lang.NullPointerException
at com.sudarabisheck.easy.GemStones.solve(GemStones.java:23)
at com.sudarabisheck.easy.GemStones.main(GemStones.java:37)
You need to initialize the Array as,
gemArray = new String[numOfStones];
The main problem is, once you've read the number of stones to be entered, you never initialise the gemArray before you use it...
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
//reading the strings
for (int i = 0; i < numOfStones; i++) {
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
You should use the numOfStones value to initialise the gemArray
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
// Intialise gemStones here...
gemStones = new String[numOfStones];
//reading the strings
for (int i = 0; i < numOfStones; i++) {
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
You never inizialize the array gmeArray so add the initialization:
public void solve() throws Exception{
Scanner in = new Scanner(System.in);
//Reading the integer
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
gemArray = new String[numOfStones];
//reading the strings
for(int i=0;i<numOfStones;i++){
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
for(int i=0;i<numOfStones;i++){
System.out.println(gemArray[i]);
}
in.close();
}