The array that returns from method contain undesirable values. I don't know why.
This is DriverExam Class:
public class DriverExam
{
private char[] answer = {'B','D','A','A','C','A','B','A','C','D',
'B','C','D','A','D','C','C','B','D','A'};
private char[] stuAnswer = new char[20];
private int totalCorrect = 0;
private int[] missed = new int[20];
public DriverExam(char stuAnswer[])
{
for (int i = 0; i < stuAnswer.length; i++)
{
this.stuAnswer[i] = stuAnswer[i];
}
}
public int gettotalCorrect()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] == answer[i])
totalCorrect++;
}
return totalCorrect;
}
public int gettotalIncorrect()
{
return 20-totalCorrect;
}
public int[] getMissed()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] != answer[i])
{
missed[k] = i;
k++;
}
}
return missed;
}
}
This is the main program:
import java.util.Scanner;
public class Main6
{
public static void main(String[] args)
{
char[] answer = new char[20];
int[] missed2;
String str;
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= 20; i++)
{
System.out.println("Enter the answer for question #"+i);
str = keyboard.nextLine();
while (Character.toUpperCase(str.charAt(0)) != 'A'
&& Character.toUpperCase(str.charAt(0)) != 'B'
&& Character.toUpperCase(str.charAt(0)) != 'C'
&& Character.toUpperCase(str.charAt(0)) != 'D')
{
System.out.println("Your input is invalid. Only accept A, B, C, or D");
System.out.println("Enter the answer for question #"+i);
str = keyboard.nextLine();
}
answer[i-1] = Character.toUpperCase(str.charAt(0));
}
DriverExam de = new DriverExam (answer);
System.out.print("***FINAL RESULT:");
System.out.print("\nTotal correct answers: "+de.gettotalCorrect());
System.out.print("\nTotal incorrect answers: "+de.gettotalIncorrect());
System.out.print("\nQuestions missed: ");
missed2 = de.getMissed();
for (int i = 0; i < missed.length; i++)
{
System.out.print(i+" ");
}
}
}
In DriverExam class I return an array named "missed" to the main program. In main program, I use an array named "missed2" to store the array returned. But when I print the result (I type all the answer with "A"). It's like below:
FINAL RESULT:
Total correct answers: 6
Total incorrect answers: 14
Questions missed: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
The question missed result is strange and incorrect.
What you want for "missed" to be is a variable length result. To do this with an array, you will need a value that signals the end of the results. Here, I've used -1.
public int[] getMissed()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] != answer[i])
{
missed[k] = i;
k++;
}
}
if(k < missed.length)
{
missed[k] = -1
}
return missed;
}
Then, in your for loop, check for the end value. The strange values are probably default int values caused by not setting them explicitly in the array.
for (int i = 0; i < missed2.length && missed2[i] != -1; i++)
{
System.out.print(i+" ");
}
Related
I have been trying to submit my code, but I am getting Runtime Error everytime. I am not able to point out the problem with my code. The code works fine on my computer, it just shows RUNTIME ERROR when I try to submit it.
I coded in IntelliJ.
import java.util.Scanner;
class practice2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = 0;
do {
t = input.nextInt(); // number of test cases
} while (t < 1 || t > 100);
int n = 0; // variable to store length of the string
int k = 0; // variable to store the goodness number
String s = "";
for (int i = 0; i < t; i++) {
do {
n = input.nextInt(); // string length
} while (n < 1 || n > 100);
do {
k = input.nextInt(); // goodness number
} while (k < 0 || k > (n / 2));
input.nextLine(); // clearing buffer
do {
s = input.nextLine();
} while (s.length() != n);
s = s.toUpperCase(); // in uppercase
int minOp = checkGoodness(s, k, n);
System.out.println("case #" + (i + 1) + ": " + minOp);
}
}
public static int checkGoodness(String s, int k, int n) {
char[] sArr = new char[s.length()];
sArr = s.toCharArray();
int score = 0; int minOp = 0;
for (int i = 0; i < sArr.length / 2; i++) {
if (sArr[i] != sArr[sArr.length - i - 1]) {
score++;
}
}
if ( score == k)
minOp = 0;
else
minOp = Math.abs(score - k);
return minOp;
}
}
Make your class public and change it's name from "practice2" to "Solution".
The most frequent runtime errors with submitting to an online judge are the incorrect name of the main class. You should check the requirements for Java and see what name for the main class should you use. Change "practice2" to that and it should work.
Instead of
s = input.nextLine();
Try
s = input.next();
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
{
int n,m;
string s;
int c=0;
cin>>n>>m;
int j=n-1;
cin>>s;
for(int k=0;k<n/2 && j>=0 ; k++)
{
if(s[k]!=s[j] )
{
c++;
}
j--;
}
cout<<"Case #"<<i<<": "<<abs(m-c);
cout<<endl;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Display the population of each country from the least to the highest.
[Input Format: First input refers to the no of countries, second one is an array to get the country names and the third one is an array to get the population of each country (the population is given in crores)]
[Assumption: no two countries will have same population]
Sample Input1:
5
Hong Kong
china
japan
australia
america
135
133
12
2
32
Sample Output1:
australia
japan
america
china
Hong Kong
2
12
32
133
135
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
String coun[] = new String[size];
int pop[] = new int[size];
for (int i = 0; i < size; i++) {
coun[i] = sc.next();
}
for (int i = 0; i < size; i++) {
pop[i] = sc.nextInt();
}
String sort_coun[] = new String[size];
int[] sort_pop = Arrays.copyOf(pop, size);
Arrays.sort(sort_pop);
for (int i = 0; i < size; i++) {
int findindex = findindex(pop, sort_pop[i]);
if (findindex != -1)
sort_coun[i] = coun[findindex];
}
for (int i = 0; i < size; i++) {
System.out.println(sort_coun[i]);
}
for (int i = 0; i < size; i++) {
System.out.println(sort_pop[i]);
}
}
public static int findindex(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target)
return i;
}
return -1;
}
}
Just add sc.nextLine(); after int size = sc.nextInt();
sc.nextInt() will not read the new line character after hitting enter. So the first character in count array will be an empty string.
Please find the working code:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
String coun[] = new String[size];
int pop[] = new int[size];
sc.nextLine();
for (int i = 0; i < size; i++) {
coun[i] = sc.nextLine();
}
for (int i = 0; i < size; i++) {
pop[i] = sc.nextInt();
}
String sort_coun[] = new String[size];
int[] sort_pop = Arrays.copyOf(pop, size);
Arrays.sort(sort_pop);
for (int i = 0; i < size; i++) {
int findindex = findindex(pop, sort_pop[i]);
if (findindex != -1)
sort_coun[i] = coun[findindex];
}
for (int i = 0; i < size; i++) {
System.out.println(sort_coun[i]);
}
for (int i = 0; i < size; i++) {
System.out.println(sort_pop[i]);
}
}
public static int findindex(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target)
return i;
}
return -1;
}
}
I don't think Joby's answer is a correct one. The InputMismatchException as in attached picture is something that occurrs if after typing N String values you unexpectedly type something that's not a number. And the problem still pops up even with the accepted answer's code. The thing is, with this code:
for (int i = 0; i < size; i++) {
pop[i] = sc.nextInt();
}
you will always get an InputMismatchException for anything else than a number. To get rid of the error, it needs to be replaced with something alomg the lines of:
int validInputCount = 0;
while (validInputCount < size) {
try {
String input = sc.next();
pop[validInputCount] = Integer.parseInt(input);
validInputCount++;
} catch (NumberFormatException e) {
System.out.println("Please enter a valid integer number:");
}
}
I am looking to input an integer between 10 and 100 into a one dimensional array, and if the value already exists anywhere in the array, do not insert it into the array, but notify user and resume input until 5 unique numbers are added.
Here is my code. I know it's not right, but you can see that what I am trying to do is use simple for loops and a search method to get the numbers, store them into the array and search for a duplicate. My problem in my code is that I can't seem to set the number I just entered as the variable 'key' which I need to send to the method 'search'.
// input an integer between 10 and 100, add to array and print results. if value is already in array, notify user, print array. keep adding to array until 5 unique values have been entered
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
list[i] = input.nextInt();
}
int count = search(list, key);
System.out.println("It has been entered.");
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].equals(key)) {
;
}
count++;
}
return (count);
}
}
Simple example with array. Could improve with alternate data structure list set.
The search() method is essentially included within the while() loop, namely the for() loop examples the search for a target number already being included.
int c = 0; is declared before the loops and makes sure to find 5 unique numbers.
import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
boolean has = n >= 10 && n <= 100;
for (int i = 0; i <= c && !has; ++i)
if (list[i] == n)
has = true;
if (!has) {
System.out.println("It has been entered.");
list[c++] = n;
}
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
}
Alternate version:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Set<Integer> set = new HashSet<Integer>(5);
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
if ((n < 10) || (n > 100) || !set.add(n))
continue;
else {
System.out.println("It has been entered.");
c++;
}
}
System.out.println("Result = " + set);
s.close();
}
}
additionally, using search()
public class App {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter number: ");
int n = s.nextInt();
if ((n >= 10 && n <= 100) && search(list, n) == 0) {
list[i] = n;
System.out.println("It has been entered.");
} else
i--;
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == key) {
count++;
}
}
return count;
}
}
Edit: also added the 10-100 spec
edit2: using your approach with search() method
You are saving the input directly in the array.
Save the input in a temporal variable which you'll pass to search. And based on result of search you add to the array or prompt for another input.
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
int temp = input.nextInt();
if(search(list,temp) == 0)
list[i] = temp;
}else{
System.out.println("It has been entered.");
i--;
}
}
I tried to implement the Fenwick Tree in Java, but I am not getting the desired result.
Here is my code:
import java.io.*;
import java.util.*;
import java.math.*;
class fenwick1 {
public static int N;
public static long[] a;
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
a = new long[N];
String[] str = br.readLine().split(" ");
for (int i = 0; i < N; i++) {
a[i] = Long.parseLong(str[i]);
}
increment(2, 10);
System.out.println(a[2]);
System.out.println(query(4));
}
public static void increment(int at, int by) {
while (at < a.length) {
a[at] += by;
at |= (at + 1);
}
}
public static int query(int at) {
int res = 0;
while (at >= 0) {
res += a[at];
at = (at & (at + 1)) - 1;
}
return res;
}
}
When I give input:
10
1 2 3 4 5 6 7 8 9 10
I get:
13
19
So the increment function works fine. But query(4) should give the cumulative sum up to index 4 i.e.
(1 + 2 + 13 + 4 + 5) = 25
You do not initialize it properly.
Instead of:
for (int i = 0; i < N; i++) {
a[i] = Long.parseLong(str[i]);
}
It should be:
for (int i = 0; i < N; i++) {
increment(i, (int)Long.parseLong(str[i]));
}
because a[i] should store a cumulative sum, not a single element.
If you want to store the initial array elements too, you can just create one more array:
long[] initA = new long[N];
for (int i = 0; i < N; i++) {
initA[i] = Long.parseLong(str[i]);
increment(i, (int)initA[i]);
}
This is My Array code with given string numbers(0098765424100304643528):
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
System.out.print(tempCharArray[i]+"->");
}
System.out.println();
}
}
this is the result after running :
0->0->9->8->7->6->5->4->2->4->1->0->0->3->0->4->6->4->3->5->2->8->
I want to change it such below (How can I fragment my array in foursome ?)
0098->7654->2410->0304->4352->8
System.out.println(StringUtils.join("0098765424100304643528".split("(?<=\\G.{4})"), "->"));
maybe you write the result is wrong as you say (foursome), if you just want the output foursome , you can do like that :
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
System.out.print(tempCharArray[i]);
if((i+1)%4==0)
{
System.out.print("->");
}
}
We will check if value of i is not 0 and i is divisible by 4. If true, then print -> else print number without it.
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
if(i > 0 && i%4 == 0)
System.out.print(tempCharArray[i]+"->");
else
System.out.print(tempCharArray[i]);
}
System.out.println();
}
}
You could check if i is dividable by 4, if it is add an arrow, otherwise just print the number. Ie:
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
if((i % 4 == 0) && i > 0)
System.out.print(tempCharArray[i]+"->");
else
System.out.print(tempCharArray[i]);
}
System.out.println();
}
}
Here the % is the modulus operator, which tells us the remainder of something divided by something else, ie: 5 % 4 = 1 since 5 / 4 = 1 * 4 + 1