I'm getting an infinite loop error but I don't know how to end the loop.
int a,b,c;
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((line=br.readLine())!=null);
{
System.out.println("Enter the two numbers to add:");
a=Integer.parseInt(line);
b=Integer.parseInt(line);
c = a+b;
System.out.println("Sum of two numbers:"+ c);
}
You need to remove ; from the end of the while loop because now you code is like
while loop without body
while((line=br.readLine())!=null);
and code block
{
System.out.println("Enter the two numbers to add:");
a=Integer.parseInt(line);
b=Integer.parseInt(line);
c = a+b;
System.out.println("Sum of two numbers:"+ c);
}
So the code will stay in the while loop forever and just read lines
Note: a and b will convert the same line to int if your line like 10 20 you need to split it into 2 string first then get every integer in the variable
String[] number = line.split(" ");
a=Integer.parseInt(numbers[0]);
b=Integer.parseInt(numbers[1]);
or you can use Scanner to read integer by integer for example
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = a+b;
System.out.println("Sum of two numbers:"+ c);
}
Try something like this:
public static void main(String[] args) throws Exception {
int a, b, c;
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Enter the two numbers to add:");
if ((line = br.readLine()) != null && !line.isBlank()) {
String[] input = line.split(" ");
a = Integer.parseInt(input[0]);
b = Integer.parseInt(input[1]);
c = a + b;
System.out.println("Sum of two numbers:" + c);
} else {
break;
}
} while (true);
}
Output:
Enter the two numbers to add:
4 5
Sum of two numbers:9
Enter the two numbers to add:
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InfLoop {
public static void main(final String[] args) throws IOException {
example1();
example2();
}
private static void example1() {
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);) {
while (true) {
final String line1 = br.readLine();
if (line1 == null) {
System.out.println("First number not entered! Aborting...");
break;
}
final String line2 = br.readLine();
if (line2 == null) {
System.out.println("Second number not entered! Aborting...");
break;
}
final int number1 = Integer.parseInt(line1);
final int number2 = Integer.parseInt(line2);
final int c = number1 + number2;
System.out.println("Result of '" + number1 + "'+'" + number2 + "'='" + c + "'");
}
} catch (final Exception e) {
e.printStackTrace();
}
}
private static void example2() throws IOException {
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);) {
while (true) {
final Integer number1 = readInteger(br, "Enter first number: ");
if (number1 == null) {
System.out.println("First number is invalid! Aborting...");
break;
}
final Integer number2 = readInteger(br, "Enter second number: ");
final String line2 = br.readLine();
if (line2 == null) {
System.out.println("Second number is invalid! Aborting...");
break;
}
final int c = number1.intValue() + number2.intValue();
System.out.println("Sum of '" + number1 + "'+'" + number2 + "'='" + c + "'");
}
}
}
private static Integer readInteger(final BufferedReader pBr, final String pMessage) {
if (pMessage != null) System.out.println(pMessage);
try {
final String line = pBr.readLine();
if (line == null) return null;
return Integer.valueOf(line);
} catch (final Exception e) {
return null;
}
}
}
/*
* 1) indentation was off, use IDE that does formatting for you
* 2) use try/resource(/catch/finally)
* 3) you need to read 2 separate lines, else a and b are the same
* 4) start using helper methods (readInteger), save you lots of duplicate code
* 5) there's two different ways of error handling here: handle inside the method (example1), or throw (example2),
* whatever is more useful for the calling code
* 6) usually handling errors (instead of throwing them) should only be done if it is a direct requirement to the method!
*/
/UPDATE: changed IOException to Exception in readInteger()
Related
Iv'e been trying to get my code to work so that the user can only input integers. However, its keeps crashing when I enter something with characters like "awsd". I've tried using a bool to help, but it only catches negative inputs. Also, the input method must start as an integer, so I cant switch it to a string. Please help.
import java.util.Scanner; // Needed for Scanner class
import java.io.*; // Needed for File I/O classes
public class Reverse {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String Continue = "yes";
int num;
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile();
//file scanner
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR, true));
while (Continue.equals("yes")) {
System.out.print("Enter an integer number greater than 0 :");
num = keyboard.nextInt();
keyboard.nextLine();
if (fileWR.exists())
{
validate(num, output);
}
else
{
fileWR.createNewFile();
}
//option if the user wants to continue
System.out.println("Do you wish to continue?(yes or no): ");
Continue = keyboard.nextLine();
}
output.close();
}
public static void validate(int num, BufferedWriter output) throws IOException {
Scanner keyboard = new Scanner(System.in);
while(!checkNum(num))
{
System.out.print("That is not an integer greater than 0, please try again: ");
num = keyboard.nextInt();
keyboard.nextLine();
}
System.out.print("The original numbers are " + num +"\n");
output.write("\r\nThe original numbers are " + num +"\r\n");
reverse (num, output);
even (num, output);
odd(num, output);
}// end of public static void validate
public static void reverse(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num); //must output result within the void method for it to count as a void method
String result = ""; //otherwise, you cannot output it in the main method.
for (int i = (input.length() - 1); i >= 0; i--)
{
result = result + input.charAt(i)+' ';
}
result = "the number reversed "+ result +"\r\n";
System.out.print(result);
output.write(result);
}// end of public static void reverse
public static void even(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num);
String result = "";
for (int i = 0; (i < input.length()); i++)
{
if (Character.getNumericValue(input.charAt(i)) % 2 == 0)
result = result + input.charAt(i) + ' ';
}
if (result == "") {
result = "There are no even digits" + "\r\n";
} else {
result = "the even digits are "+ result +"\r\n";
}
System.out.print(result);
output.write(result);
}// end of public static void even
public static void odd(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num);
String result = "";
for (int i = 0; (i < input.length()); i++)
{
if (Character.getNumericValue(input.charAt(i)) % 2 == 1)
{
result = result + input.charAt(i) + ' ';
}
}
if (result == "") {
result = "There are no odd digits" + "\r\n";
} else {
result = "the even odd digits are "+ result +"\r\n";
}
System.out.print(result);
output.write(result);
System.out.print("------------------------\n");
output.write("------------------------\n");
}// end of public static void odd
public static boolean checkNum(int num)
{
if(num > 0) {
return true;
}
else {
return false;
}
}
}
You should first get the String, and then try to cast it:
try {
String numStr = keyboard.nextLine();
num = Integer.parseInt(numStr);
//Complete with your code
} catch (NumberFormatException ex) {
System.out.print("That is not an integer");
}
I want to find the sum of array of integers using recursion and taking input with only one line like 1 2 3 4 5.What methods can i use to collect the data from the scanner because now i have only number format exception.
I tried to run it with initialized array and with all elements inputed on a new and it works but doesnt when i go for one line input like 1 2 3 4 5 like i have already mentioned
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
int[] arr = new int[5];
int index = 0;
int sum = arraySum(arr, index);
System.out.println(sum);
}
static int arraySum(int[] arr, int index) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
arr[index] = Integer.parseInt(input.trim());
Scanner scanner = new Scanner(input);
if(scanner.hasNext()) {
if (scanner.hasNextInt()) {
int currentSum = arr[index] + arraySum(arr, index + 1);
return currentSum;
}
}
return 0;
}
}
You could do something like this, where you read a line of input first, then pass it to a Scanner and sum up the various int values. This will loop forever – it's just an example to show you how it could work.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
int total = 0;
Scanner scanner = new Scanner(reader.readLine());
while (scanner.hasNextInt()) {
total += scanner.nextInt();
}
System.out.println("total: " + total);
}
Or you could use String.split():
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
String[] parts = line.split("\\s+"); // split on one or more whitespace characters
int total = 0;
for (String part : parts) {
total += Integer.parseInt(part);
}
System.out.println("total: " + total);
Or you could use a StringTokenizer:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
int total = 0;
while (tokenizer.hasMoreTokens()) {
total += Integer.parseInt(tokenizer.nextToken());
}
System.out.println("total: " + total);
Here is a solution using recursion.
It first will read the input line and split it into tokens. nextLine() will grab the the whole line as a string, and split(" ") will split it into an array of tokens on each " ".
Then it will recursively calculate the sum of the values as integers in that array. The recursive step uses an offset value to know where it is in the array. It will add the current value, starting at arr[0], to the remainder of the recursion with the offset iterating in the recursive call.
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
String[] inputTokenArray = getInputArray();
Integer sum = recursiveArraySum(inputTokenArray, 0);
System.out.println(sum.toString());
}
public static String[] getInputArray() {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
return input.split(" ");
}
public static Integer recursiveArraySum(String[] arr, Integer offset) {
if (offset + 1 > arr.length) {
return 0;
}
return Integer.parseInt(arr[offset]) + arraySum(arr, offset + 1);
}
}
Can also be simplified, for example:
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
String[] inputTokenArray = new Scanner(System.in).nextLine().split(" ");
Integer sum = arraySum(inputTokenArray, 0);
System.out.println(sum.toString());
}
public static Integer arraySum(String[] arr, Integer offset) {
return (offset + 1 > arr.length) ? 0 : Integer.parseInt(arr[offset]) + arraySum(arr, offset + 1);
}
}
You can use a BufferReader and a Scanner to read each int in the line and sum them up at the same time.
System.out.print("Enter numbers: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(reader.readLine());
int sum = 0;
while(in.hasNext()) {
sum += in.nextInt();
}
System.out.println("Sum = " + sum);
Console:
Enter numbers: 1 2 3 4 5
Sum = 15
I'm trying to get it so when it reads through the file, it splits every thing before a comma into an element, and then since there are 10 integer grades, those need to be parsed into an int and then calculated for an average. However, I'm unsure of how to actually accomplish this. I've been looking for a solution for hours and I just can't seem to figure it out. I would really appreciate some help here, as I'm currently running out of brain cells.
Thank you, - from someone new to programming.
The assignment:
https://i.stack.imgur.com/L7E9x.png
The .txt file I'm reading from:
https://i.stack.imgur.com/nxCi4.png
My current code:
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String userInput;
System.out.println("Enter raw grades filename:");
userInput = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line = "";
String txtSplitBy = ", ";
while ((line = br.readLine()) != null) {
String[] splitLine = line.split(", ");
String name = splitLine[0];
String scores = splitLine[2];
int i = Integer.parseInt(scores);
}
}
}
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line;
String txtSplitBy = ",";
while ((line = br.readLine()) != null) {
int score = 0;
String grade;
String[] splitLine = line.split(txtSplitBy);
String name = splitLine[0];
for ( int i =1; i <= 10; i++) {
score += Integer.parseInt(splitLine[i]);
}
if ( score < 50 ) {
grade = "B";
}else if ( score < 60 ) {
grade = "A";
}else {
grade = "S";
}
System.out.println(name +"," + (score/10) + "," + grade );
}
You need to add your grade logic here.
Here is my version, I kept it simple, after all, it's your homework!
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String userInput;
System.out.println("Enter raw grades filename:");
userInput = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line = "";
String txtSplitBy = ","; // Changed from ', ' to ','
while ((line = br.readLine()) != null) {
String[] splitLine = line.split(",", 2); // The threee caps the number of splits
String name = splitLine[0];
ArrayList<Integer> grades = new ArrayList<>();
String[] rawGrades = splitLine[1].split(","); // List of grades as string
for(String rawGrade : rawGrades) {
grades.add(Integer.parseInt(rawGrade));
}
}
}
In the main method I am reading the input from system.in and passing it to while condition. But it is not working. Each time it takes default 53 cases. Could not figure out where is the mistake.
If I manually assign int num = 15 instead of int num = br.read() just above the while loop. It works fine.
public class Parenthesis
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int num = br.read();
while(num > 0)
{
System.out.println(num-- + "Chances Left");
String str = br.readLine();
if(isParenthesis(str))
System.out.println("Cool Rudra");
else
System.out.println("Poor Rudra");
}
}
public static boolean isParenthesis(String str)
{
if(str == "Rudra")
return true;
else
return false;
}
}
Use below
int num = Integer.parseInt(br.readLine());
instead of
int num = br.read();
Another way to get intfrom user
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
I wanna develop java program with following task.
use enter file name and also enter product code. and as result its show all products details
for example.
file data is MLK#milk#expired date 15 may 2016
output will be
this product name is milk with MLK code and will expired in 15 may 2016.
help me thanks...
my code is...
import java.io.*;
import java.util.*;
public class search
{
public static void main( String[] args ) throws IOException
{
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("stationMaster.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
while(file.hasNextLine())
{
String data=file.nextLine();
System.out.println(data);
}
//System.out.println("");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Station does not exist");
break;
}
}
}
}
package main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String tokens[] = null;
String code, product, date;
try {
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
tokens = line.split("#");
code = tokens[0];
product = tokens[1];
date = tokens[2];
System.out.println("this product name is " + product
+ " with " + code
+ " code and will expired in"
+ date.substring(12));
line = br.readLine();
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found exception.");
} catch (IOException e) {
System.out.println("IO Eception occered.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
public class search
{
public static void main( String[] args ) throws IOException
{
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("stationMaster.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
//split the string on # character so that you get code, product name and expiration date separately.
String arr[] = line.split("#");
//check whether the string contains the required string or not
try{
if(arr[0].equalsIgnoreCase(word) || arr[1].equalsIgnoreCase(word)){
//line break
System.out.println();
//split the format 'expiration date 15 may 2016' so that we can use date separately without the heading of 'expiration date'
String dateStrings[] = arr[2].split(" ");
System.out.print("this product name is " + arr[1] + " with " + arr[0] + " code and will expire on ");
System.out.println(dateStrings[2] + " " + dateStrings[3] + " " + dateStrings[4]);
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
catch(IndexOutOfBoundsException indexEx){
val = 0;
continue;
}
}
if(val == 0){
System.out.println("Station does not exist");
break;
}
}
}
}
The above code will search the string that will be read from the file if it contains the word to search or not. It can be product code or product name