I'm trying to read integers from a .txt file and I get this error directly after input even though the while loop contains hasNextInt to make sure there is another integer in the file to read.
import java.util.Scanner;
import java.io.*;
public class Part2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String prompt = ("Please input the name of the file to be opened: ");
System.out.print(prompt);
String fileName = input.nextLine();
input.close();
Scanner reader = null;
try{
reader = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){
System.out.println("--- File Not Found! Exit program! ---");
}
int num = 0;
while(reader.hasNextInt()){
reader.nextInt();
num++;
}
int[] list = new int[num];
for(int i = 0; i<num; i++){
list[i] = reader.nextInt();
}
reader.close();
System.out.println("The list size is: " + num);
System.out.println("The list is:");
print(list);//Method to print out
}//main
}//Part2
This is because in while loop , you have reached the end of the file.
while(reader.hasNextInt()){
reader.nextInt();
num++;
}
try to reinitialize it again after the while loop.
reader = new Scanner(new File(fileName));
I think it's better to use List like
List list = new ArrayList();
int num = 0;
while(reader.hasNextInt()){
list.add(reader.nextInt());
num++;
}
/* this part is unnecessary
int[] list = new int[num];
for(int i = 0; i<num; i++){
list[i] = reader.nextInt();
}
*/
//then
System.out.print(list);
Related
Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}
This question already has answers here:
How to read from user's input in Java and write it to a file
(2 answers)
Closed 7 years ago.
public static void main(String[] args) throws FileNotFoundException {
#SuppressWarnings("unused")
Scanner in = new Scanner(System.in);
System.out.println("enter filename");
Filename=in.next();
PrintWriter outputFile =new PrintWriter(Filename);
outputFile.println();
outputFile.close();
getInput();
display();
}
public static void display() throws FileNotFoundException{
for (int i = 0; i < genders.length; i++) {
System.out.println(ages[i]+";"+genders[i]+";"+emails[i]+";"+salaries[i]);
}}
public static void getInput(){
System.out.print("How many users do you wish to enter: ");
int num = in.nextInt();
ages= new int[num];
genders = new String[num];
emails = new String[num];
salaries = new double[num];
for (int i = 0; i < num; i++) {
System.out.print("Please enter your age for person "+(i+1)+": ");
ages[i] = in.nextInt();
while (ages[i]<20 ||ages[i]>30){
System.out.println("invalid age please re enter again");
ages[i] = in.nextInt();}
in.nextLine();
hey guys i am trying to write the contents of user input into a file. my problem is it creates the file but doesnt write to it. i have tried various methods but doesnt work any help?
Filename=in.next();
PrintWriter outputFile =new PrintWriter(Filename);
outputFile.println();
I think you are creating the file with the name of user input, and prints an empty line to it
Your question is answered here: https://stackoverflow.com/questions/18070629/how-to-read-from-users-input-in-java-and-write-it-to-a-file
But to summarise: You are simply creating a file named after the user's input. You need to actually write that information to the file:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
private static String fileName;
private static String[] genders, emails;
private static double salaries[];
private static int userCount;
private static int[] ages;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
System.out.println("enter filename");
fileName = in.nextLine();
File myFile = new File(fileName);
getInput();
display();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter(myFile);
writer = new BufferedWriter(fWriter);
writer.write(display().toString());
writer.newLine();
writer.close();
} catch (Exception e) {
System.out.println("Error!");
}
}
public static ArrayList<String> display() throws FileNotFoundException {
ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < genders.length; i++) {
data.add(ages[i] + ";" + genders[i] + ";" + emails[i] +
";" + salaries[i]);
}
for (int i = 0; i < genders.length; i++) {
System.out.println(ages[i] + ";" + genders[i] + ";" + emails[i] +
";" + salaries[i]);
}
return data;
}
private static void getInput() {
System.out.print("How many users do you wish to enter: ");
int userCount = in.nextInt();
ages = new int[userCount];
genders = new String[userCount];
emails = new String[userCount];
salaries = new double[userCount];
for (int i = 0; i < userCount; i++) {
System.out.print("Please enter your age for person " + (i + 1) +
": ");
ages[i] = in.nextInt();
while (ages[i] < 20 || ages[i] > 30) {
System.out.println("invalid age please re enter again");
ages[i] = in.nextInt();
}
in.nextLine();
}
}
}
I have to write a program that reads in a sequence of integers until 'stop' is entered, store the integers in an array and then display the average of the numbers entered. I'm getting an input mismatch exception when entering 'stop' so it doesn't really work, but I have no idea why. Help would be greatly appreciated.
import java.util.Scanner;
public class MeanUsingList {
public void mean() {
String s;
int n = 0;
int i = 1;
int[] array = { n };
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt();
s = in.nextLine();
} while (s != "stop");
{
System.out.println("Enter an integer");
Scanner in2 = new Scanner(System.in);
int x = in2.nextInt();
array[i] = x;
i++;
}
int av = 0;
for (int y = 0; y < array.length; y++) {
av += array[y];
}
System.out.println(av);
}
public static void main(String[] args) {
MeanUsingList obj = new MeanUsingList();
obj.mean();
}
}
First int[] array = { n }; just creates an array with 0 as the element in it.
the logic inside it will never execute while (s != "stop");
You want something like this
List list = new ArrayList();
//instead of array used arraylist because of dynamic size
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt(); //get the input
list.add(n); // add to the list
Scanner ina = new Scanner(System.in); // need new scanner object
s = ina.nextLine(); //ask if want to stop
} while (!s.equals("stop")); // if input matches stop exit the loop
System.out.println(list); // print the list
I recommend you to learn the basics
String s[];
System.out.println("Enter loop value");
int t = s.nextInt();
for(int i=0;i<t;i++)
{
str[i]=s.nextLine();
}
while it reading it gives null pointer exception
What you need is something like this:
Scanner s = new Scanner(System.in);
System.out.println("Enter loop value");
int t = s.nextInt(); // read number of element
s.nextLine(); // consume new line
String str[] = new String[t];
for(int i=0;i<t;i++)
{
str[i]=s.nextLine();
}
System.out.println(Arrays.toString(str));
Hope this helps.
I changed the typos and missing declarations in your code:
package snippet;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Snippet {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String str[] = new String[10];
System.out.println("Enter loop value (maximum 9)");
int t = s.nextInt();
for (int i = 0; i <= t; i++) {
str[i] = s.nextLine();
}
System.out.println("your entered lines:");
System.out.println(Arrays.toString(str));
}
}
However, I would recommend to store the values in a List instead of an Array. I also prefer using a BufferedReader to using a Scanner.
Try something like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter loop value");
String a[] = new String[Integer.parseInt(br.readLine())];
for (int i = 0; i < a.length; i++) {
a[i] = br.readLine();
}
//After modifying my code works well
import java.io.*;
import java.util.Scanner;
class Sample
{
public static void main(String[] args) throws Exception
{
bufferedReader();
scanner();
}
static void bufferedReader()throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Number of Strings");
int len = Integer.parseInt(br.readLine());
String a[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("Enter String"+ (i+1));
a[i] = br.readLine();
}
for(String str : a)
System.out.println(str);
}
static void scanner(){
Scanner s = new Scanner(System.in);
System.out.println("Enter Number of Strings");
int len = Integer.parseInt(s.nextLine());
String a[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("Enter String"+ (i+1));
a[i] = s.nextLine();
}
for(String str : a)
System.out.println(str);
}
}
But when using Scanner nextLine() skips the data when read
if any one knows please post description with example
I need help figuring out how to loop my IOException (in where I ask for a filename until a valid one is entered). I need a loop that somehow recognizes that an invalid file was entered and am unsure how to do this.
import java.util.*;
import java.io.*;
public class JavaGradedLab {
public static void main(String[] args) throws IOException {
Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
String nextItem;
int nextInt = 0;
int i = 0;
while (fScan.hasNextLine())
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}
Well, there's sure to be someone explaining how to make your code better via best practices etc., but as a very basic answer which in itself can probably be improved (assuming that your code works when the input is valid):
while(true) {
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
break;
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
}