When I input Y (trying to run this program again), it does not compile. The first time is good.
But the second try is not working.
I don't know what is going on, please help me through this.
The program is like reading a seat arrangement file and put them into a 2D array. I am trying to use the function to read the file and display the seat arrangement. But it can only run one time.
package Tickets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt")));
int rows = 0;
int cols = 0;
char again;
Scanner input = new Scanner(System.in);
do
{
displayMenu();
switch(input.nextInt())
{
case 1:
System.out.println("\tReserve seat\t\n");
readFile(sc,rows,cols);
// Get user input
int rowNumber = 0;
char startingSeatNumber = 'Y';
break;
case 2:
System.out.println("Exiting the program");
System.exit(0);
break;
default:
System.err.println("Unrecgnized option");
}
System.out.println("Again?(Y/N)");
again = input.next().charAt(0);
}while (again == 'Y' || again == 'y');
}
public static List<String> readFile(Scanner sc, int rows, int cols) throws Exception
{
List<String> stringList = new ArrayList<>();
while (sc.hasNext())
{
stringList.add(sc.nextLine());
}
rows = stringList.size();
cols = 0;
if (rows > 0 )
{
cols = stringList.get(0).length();
}
// Display current seating.
char[][] auditorium = new char[rows][cols];
char alphabet = 'A';
for (int i = 1; i <= stringList.get(0).length(); i++)
{
System.out.print(" " + alphabet);
alphabet++;
}
System.out.println();
for (int r = 0; r < rows; r++)
{
System.out.print((r+1 ) );
for (int c = 0; c < cols; c++)
{
auditorium[r][c] = stringList.get(r).charAt(c);
System.out.print(auditorium[r][c]+ " ");
}
System.out.println();
}
return stringList;
}
public static void displayMenu()
{
System.out.println("1. Reserve Seats\n2. Exit");
}
}
Error message:
ok here is what is going on,
you created Scanner sc in you static void main method which you then pass to readFile. you read the file and update the stringList list object.
1) iteration one proceeds as it should since it is the first pass on the file and Scanner object has not yet opened the buffer. It opens it, reads it and the stringList is populated.
2) in iteration two, the same scanner object is passed! but the object has already read the entire buffer! so the following never executes:
while (sc.hasNext())
{
stringList.add(sc.nextLine());
}
and then you run into a runtime exception (out of bounds ) when you try to access the stringList.get(0).length() since it is an empty list!
please try to create a local Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt"))); inside the readFile method instead of passing the sc object.
Related
i am trying to solve codechef question i am able to get the output in IDE and also with custom input, when i try to run with there inputs then it gives me the error
link to question:
https://www.codechef.com/problems/HS08TEST
Code:
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
int numberOne = input.nextInt();
float numberTwo = input.nextFloat();
float reduction = 0;
float result = 0;
DecimalFormat df2 = new DecimalFormat(".00");
if(numberOne > 0 && numberOne <= 2000 & numberTwo >= 0 && numberTwo <= 2000){
if(numberOne % 5 == 0){
reduction = (float)numberOne+(0.50f);
if(reduction <= numberTwo){
result = numberTwo-reduction;
System.out.println(df2.format(result));
}
if(reduction > numberTwo){
System.out.println(df2.format(numberTwo));
}
}
else{
System.out.println(df2.format(numberTwo));
}
}
}
}
Error:
Exception in thread "main" java.util.NoSuchElementException at
java.util.Scanner.throwFor(Scanner.java:862) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
Codechef.main(Main.java:14)
The "error" is caused by the input not been parsable as the required type (ie, Scanner can not either parse the input as int or float)
"A" solution would be to take the input and manually parse it. You could use nextLine and run another Scanner over it, or split on a common delimiter, or you could simple use next, for example...
import java.text.DecimalFormat;
import java.util.Scanner;
class Codechef {
public static void main(String[] args) throws java.lang.Exception {
Scanner input = new Scanner(System.in);
String element = input.next(); // Next value up to the next space or new line...
int numberOne = Integer.parseInt(element);
element = input.next(); // Next value up to the next space or new line...
float numberTwo = Float.parseFloat(element);
float reduction = 0;
float result = 0;
DecimalFormat df2 = new DecimalFormat(".00");
if (numberOne > 0 && numberOne <= 2000 & numberTwo >= 0 && numberTwo <= 2000) {
if (numberOne % 5 == 0) {
reduction = (float) numberOne + (0.50f);
if (reduction <= numberTwo) {
result = numberTwo - reduction;
System.out.println(df2.format(result));
}
if (reduction > numberTwo) {
System.out.println(df2.format(numberTwo));
}
} else {
System.out.println(df2.format(numberTwo));
}
}
}
}
This assumes that the input is provided, generally, on a single line, but this method will allow you to deal with two seperate inputs. But without know exactly what the inputs are, it's hard to provide a more precise solution
You're not consuming the space between the input values.
Just read the first line using nextLine, and then split and parse the numbers accordingly
A simple thing worked for me ....
i only surrounded the code by try and catch....
final working code...
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
try{
int n, sum = 0;
Scanner s = new Scanner(System.in);
n = s.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
int largest=0;
int element=0;
for(int i = 0; i < n; i++){
for(int j=0;j<n;j++){
element=a[i]%a[j];
if(largest<element){
largest=element;
}
}
}
System.out.println(largest);
}
catch(Exception e){
}
}
}
I was trying a question from UVA (10324) but always keep on getting Time Limit in the soution. I am pretty sure the code is correct but still the code goes into infinite loop. I have tried this question 6 times but can't seem to pass it.
Can someone shed some light on what could be wrong:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int ii=1;
boolean flag = false;
while(sc.hasNextLine()){
String str = sc.nextLine();
if(str.trim().isEmpty())
break;
int TC = sc.nextInt();
System.out.println("Case " +ii+++":");
while(TC-->0){
flag = false;
int a = sc.nextInt();
int b = sc.nextInt();
int c=0;
if(a>b){
c=a;
a=b;
b=c;
}
c = str.charAt(a)-'0';
for(int i=a+1;i<=b;i++){
if(str.charAt(i)-'0' != c){
flag = true;
break;
}
}
System.out.println(flag?"No":"Yes");
}
try{
sc.nextLine();
}
catch(Exception ex){
break;
}
}
}
}
It's the running of the for(int i=a+1;i<=b;i++) loop inside the while loop that's inefficient. This has to scan through most of the string each time.
Because there are multiple test cases for each input string, then you can create another data structure that's more efficient to query.
Before the while loop, create an array that stores the number of times the characters have changed since the start of the string, for each position:
int total = 0;
int changes[] = new int[str.length()];
for(int i = 1; i < changes.length; i++) {
if(str.charAt(i) != str.charAt(i - 1)) {
total++;
}
changes[i] = total;
}
Then the flag can be set as:
boolean flag = (changes[a] != changes[b]);
Hi guys sorry I'm a newbie to Java, this is one of the exercise in my class.
I supposed to ask user input 5 numbers, then compare them if they are the same number that entered before.
These are my code so far, but I can't get it work.
Thanks.
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
You may want something like this:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}
Hi I'm trying to make a simple program that prints out the elements
of a list.The catch is that the list should be dynamically initialized from
the console(the user must be able to input as much as elements he wants),and
then the program has to print on the console.
I wrote this code,but it's giving me some errors at line 13:
Error:
Multiple markers at this line
Syntax error on token "(", ; expected
void is an invalid type for the variable-"keyPressed"
Syntax error on token ")", ; expected
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
public class test2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
void keyPressed(KeyEvent e) {
for(Integer i = 0;i < list.size();i++){
i = (Integer) in.nextInt();
list.add(i);
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println();
}
}
}
}
}
keyPressed method has to be defined outside the main method. Also, the body of your for loop won't be executed as the list is empty. You need to loop - "while" - until the user inputs the "KeyEvent.VK_ENTER" and then exit the loop and print the list.
Probably easier to do something like this instead of trying to capture each key press:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
while(in.hasNextInt())
{
list.add(in.nextInt());
}
System.out.println("Invalid integer entered.");
System.out.println("List contents:");
for(int i : list)
{
System.out.print(i + " ");
}
}
}
Scanner in = new Scanner(System.in);
int nextInt = in.nextInt();
List<Integer> list = new ArrayList<>(nextInt);
for (int i = 0; i < nextInt; i++) {
list.add(in.nextInt());
}
for (Integer integer : list) {
System.out.println(integer);
}
code to store and print value of dynamic length of list with dynamic value input
im getting an error everytime i try to run my hangman code. Using ready to program IDE, if i hit run it just highlights import java.util.Scanner statement and tells me it is not valid.(import java.util.Scanner is not valid,since it does not name a type in a package. that is exactly what it tells me).
I am new to this so i would appreciate if anyone could correct the code and just post it as a reply :) thanks.
package HangmanSummative;
import java.lang.System.out;
import java.util.Scanner;
class Game
{
public static void main (String[] args)
{
int LivesLeft;
String LetterGuessed;
String wordInput;
char[] hiddenWord;
char[] aOfWord;
Scanner input = new Scanner (System.in);
boolean isFound;
int a;
public Game ()
{
this.setLives (10);
system.out.println (" Player one enter a word:");
wordInput = input.nextline ();
aOfWord = wordInput.toCharArray ();
hiddenWord = new char [aOfWord.length];
for (int j = 0 ; j < hiddenWord.length ; j++)
hiddenWord [j] = '*';
this.output ();
while (LivesRemaining > 0)
{
system.out.println (" Choose a letter: ");
LetterGuessed = input.nextLine ();
this.checkForMatch (LetterGuessed);
if (isFound == true)
{
hiddenWord [a] = LetterGuessed.charAt (0);
}
else
{
system.out.println(" Not found.");
this.reduceLives();
}
this.output();
}
}
public void setLives (int a)
{
this.LivesRemaining = a;
}
public void reduceLives()
{
LivesRemaining = LivesRemaining -1;
system.out.println("Lives left:" + this.getLives());
}
public int getLives()
{
return LivesRemaining;
}
public void output ()
{
system.out.println("Lives left" + this.getLives ());
system.out.println("Progress so far ");
for (int i = 0; i <hiddenWord.length; i++)
{
system.out.print(hiddenWord[i] + "\n");
}
}
public void checkForMatch(String l)
{
for(int i=0; i< aOfWord.length; i++)
{
if(l.charAt(0) == aOfWord[i])
{
isFound=true;
a = i;
break;
}
else
{
isFound = false;
}
}
}
}
}
There are tons of compilation errors in your program. First you can't declare methods or constructors in other methods. Your main method seems to contain a Game constructor. That is not syntactically correct. Second, gGet rid of this line
import java.lang.System.out;
It's is not correct because out is a static member. Remember that the java.lang package is always imported implicitly. You could technically do
import static java.lang.System.out;
if you wanted to do
out.println("whatever");
directly instead of
System.out.println("whatever");
but you aren't doing that so the import is unnecessary.
Third, it's System, not system.
Fourth, its Scanner#nextLine(), not Scanner#nextline() as you have here
wordInput = input.nextline();
Finally, there's no instance variable called LivesRemaining declared anywhere.
You have to use System.out.println everywhere instead of system.out.println. s should be Uppercase.When you are doing import static System.out , you can directly use out.println to print statements in your code. That's the real usage of static import statements in your code. Using static imports should be mostly avoided because it creates confusion to the reader. Try to always use System.out.print in your code wherever needed.