Question

In: Computer Science

Is there anyway to solve below problem in Java? Wherever there is int it gives an...

Is there anyway to solve below problem in Java?

Wherever there is int it gives an error! It's not only line 20! it give an runtime error everywhere get int after string! or even before read string!

cities[i] = sc.next(); //This way does not work!!!!

==============

input

San Francisco
Las Vegas
8
San Diego
Los Angeles
San Francisco
San Jose
Sacramento
Santa Barbara
Las Vegas
Pheonix
8 19
0 1
0 3
1 0
1 2
1 4
1 3
2 1
2 5
2 6
2 7
3 7
3 0
3 1
4 7
4 1
5 2
6 2
7 2
7 3

==============

Error:

==============

Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:864)
        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 Solution.main(myFuncs.java:20)

=======================

==============

import java.io.*;
import java.util.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;


public class myFuncs{

    public static void main(String arg[]) {
        Scanner sc = new Scanner(System.in);
        String s1, s2;
        s1 = sc.nextLine(); //first city
        s2 = sc.nextLine(); //second city
        int n = sc.nextInt(); //total number of cities
        String cities[] = new String[n];
        for (int i = 0; i < n; i++) {
            cities[i] = sc.nextLine(); //getting each city and storing them
        }
        n = sc.nextInt();
        int e = sc.nextInt();
        int adj[][] = new int[n][e];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < e; j++)
                adj[i][j] = 0;
        for (int i = 0; i < e; i++) {
            int c1 = sc.nextInt();
            int c2 = sc.nextInt();
            adj[c1][c2] = 1;
            adj[c2][c1] = 1;
        }

        int index1 = -1, index2 = -1;

        for (int i = 0; i < n; i++) {
            if (cities[i].equals(s1)) index1 = i; //storing the index of first city
            if (cities[i].equals(s2)) index2 = i; //storing the index of second city
        }

        adj[index1][index2] = 0;
        adj[index2][index1] = 0;


        System.out.println(cities[index1] + " " + index1);
        System.out.println(cities[index2] + " " + index2);


        if (bfs(adj, index1, index2, n)) System.out.println("true");
        else System.out.println("false");
    }

    public static boolean bfs(int adj[][], int source, int dest, int V) {

        boolean visited[] = new boolean[V];

        LinkedList < Integer > queue = new LinkedList < Integer > ();

        visited[source] = true;
        //visited[dest]=true;
        queue.add(source);

        while (queue.size() != 0) {

            int s = queue.poll();

            if (queue.size() != 0)
                queue.remove();

            System.out.print(s + " ");

            for (int i = s; i < V; i++) {
                if (adj[s][i] == 1 && !visited[i]) {
                    visited[i] = true;
                    queue.add(i);
                    if (i == dest) return true;
                }
            }

        }

        return false;
    }

}

Solutions

Expert Solution

In case of any query, do comment. Please rate answer as well. Thanks

There are two ways:

First Way: Actually you are using int n = sc.nextInt() in line 15 and pressing enter so it is taking first item of cities array as blank. So either you press only space , it will work for you. So when you use nextInt() you have to just press space after that.

I have only provided the space after third input then your old program also worked. Please see the output.

Second way: or modify the line 20 and other lines where you are taking integer input as below, then if you press enter it will work for you:

int n = Integer.valueOf(sc.nextLine());

Output:


Related Solutions

For each problem below, write a java program to solve it, name your programs as PA2_1.java...
For each problem below, write a java program to solve it, name your programs as PA2_1.java and PA2_2.java. 1. We have a steam heating boiler whose bursting pressure is known, but we of course want to use it only at pressures well below this limit. Our engineers recommend a safety factor of 3; that is, we should never exceed a pressure that is one-third of the rated bursting pressure. Write a java program that reads in the rated bursting pressure...
Problem 2 Write a program in Java to implement a recursive search function int terSearch(int A[],...
Problem 2 Write a program in Java to implement a recursive search function int terSearch(int A[], int l, int r, int x) that returns the location of x in a given sorted array of n integers A if x is present, otherwise -1. The terSearch search function, unlike the binary search, must consider two dividing points int d1 = l + (r - l)/3 int d2 = d1 + (r - l)/3 For the first call of your recursive search...
Java Palindrome (Timelimit: 10seconds) Problem Description Write a Java program to solve the following problem. A...
Java Palindrome (Timelimit: 10seconds) Problem Description Write a Java program to solve the following problem. A palindromic number is an integer that is the same when the digits are reversed. For example, 121 and 625526 are palindromic, but 625 is not a palindromic number. Input: The input is in ‘palindrome.txt’. The first line of the input contains the line count m (1 ≤ m ≤ 1,000), which is the number of lines that follows the first line. Each of the...
Java Recursion (Timelimit: 3 seconds) Problem Description Write a Java program to solve the following problem....
Java Recursion (Timelimit: 3 seconds) Problem Description Write a Java program to solve the following problem. Recursion may appear in various contexts and in different forms. For fast implementation, we should always aim at transforming recursions into a simpler form of computation. In this assignment, the task is to evaluate X(·), which is defined as follows:               |0,if m = 0 or n = 0               | X(m,n−1),if n is odd and m is even X(m,n) = | X(m−1,n),if m...
JAVA: Use existing Java Stack class to solve the "Balancing Symbols" problem. The symbols are (),...
JAVA: Use existing Java Stack class to solve the "Balancing Symbols" problem. The symbols are (), [], and {}, and each opening symbol must have a corresponding closing symbol as well as in correct order. Ignore operands and arithmetic operators since they are not relevant to our problem. You can assume each token is separated by spaces. For example: { ( a + b ) * c1 } – valid { ( a + b ) * c1 ] –...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] =...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] = 0;} catch(ArithmeticException e){array[2] = 0} // ? finally{ return 0;}} Could you please tell me why the line with the question mark will not report an error?
Use the data below to solve. The data gives the square footage and sales prices for...
Use the data below to solve. The data gives the square footage and sales prices for several houses in Bellevue, Washington. Use this information to solve the following: PLEASE SHOW YOUR WORK : ) 1) You plan to build a 500 square foot addition to your home. How much do you think your home value will increase as a result? 2) What percentage of the variation in home value is explained by the variation in the house size? 3) A...
Solve this comp architecture problem: Supposed you have an array int* arr = {3,7,6,4,5}. The values...
Solve this comp architecture problem: Supposed you have an array int* arr = {3,7,6,4,5}. The values in arr store in the memory of 0(x21), 8(x21), .... , 32(x21). Transform the following RISC-V code into a C program. ld x5, 16(x21) addi x6, x0, 3 sll x5, x5, x6 sd x5, 8(x21)
Write a method (in Java) that will return output as stated below: toThePowerOf(int): Applies exponentiation to...
Write a method (in Java) that will return output as stated below: toThePowerOf(int): Applies exponentiation to the existing PolyTerm. For example, 2.4x^3 to the power of 3 should return 13.824x^9 while 2.4x^3 to the power of -3 should return 0.0723x^-9 Respective JUnit test for this question: public void testToThePowerOf() {        assertEquals(1, t1.toThePowerOf(3).coefficient, 0.0001);        assertEquals(3, t1.toThePowerOf(3).exponent);        assertEquals(13.824, t2.toThePowerOf(3).coefficient, 0.0001);        assertEquals(9, t2.toThePowerOf(3).exponent);        assertEquals(0.0723, t2.toThePowerOf(-3).coefficient, 0.0001);        assertEquals(-9, t2.toThePowerOf(-3).exponent);        assertEquals(-0.2962,...
Java Collatz Conjecture (Timelimit: 3 seconds) Problem Description Write a Java program to solve the following...
Java Collatz Conjecture (Timelimit: 3 seconds) Problem Description Write a Java program to solve the following problem. The Collatz conjecture is about a sequence: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT