Javaのエラーについて質問

このQ&Aのポイント
  • 下記のコードでエラーが発生し、原因と改善方法を教えてください。
  • Javaのエラーについての質問です。下記のコードでUnsupportedOperationException()のエラーが発生します。原因と改善方法についてご教示願います。
  • Javaのエラーについての質問です。下記のコードでエラー、UnsupportedOperationException()が発生します。原因と改善策をお教えください。
回答を見る
  • ベストアンサー

javaのエラーについて質問

毎度、お世話になります。 下記のコードに於いて、コメント箇所でエラー(UnsupportedOperationException())が発生します。 Q1)このエラーの原因と、改良をご教授ください。 ============================= import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.Date; import java.util.Random; public class Main { public static void main(String[] args) { Random random = new Random(); random.setSeed((int) new Date().getTime()); ByteBuffer byteBuffer = ByteBuffer.allocate(10000 * 4); long start = System.currentTimeMillis(); ByteOrder order; ByteBuffer tmpBuffer; int[] ints; IntBuffer intBuffer; long end; // ビックエンディアン order = ByteOrder.BIG_ENDIAN; tmpBuffer = byteBuffer.order(order); ints = tmpBuffer.asIntBuffer().array(); //エラー発生:UnsupportedOperationException() intBuffer = IntBuffer.wrap(ints); System.out.println("ビックエンディアンで実行"); printChunk(random, ints, intBuffer); end = System.currentTimeMillis(); System.out.print("経過時間:"); System.out.println((end - start) + "msec\t"); // リトルエンディアン start = System.currentTimeMillis(); order = ByteOrder.LITTLE_ENDIAN; tmpBuffer = byteBuffer.order(order); ints = tmpBuffer.asIntBuffer().array(); //エラー発生:UnsupportedOperationException() intBuffer = IntBuffer.wrap(ints); System.out.println("リトルエンディアンで実行"); printChunk(random, ints, intBuffer); end = System.currentTimeMillis(); System.out.print("経過時間:"); System.out.println((end - start) + "msec\t"); } ========================================= 以上

  • Java
  • 回答数4
  • ありがとう数2

質問者が選んだベストアンサー

  • ベストアンサー
  • yossy_kt
  • ベストアンサー率50% (103/203)
回答No.4

すみません、最初のコードは本来やりたいことを理解しないまま、エラー回避だけのその場しのぎで書いたものなので、申し訳ありませんが忘れて頂けると幸いです。 代わりに、元のご質問のコードでエラーが発生する理由について回答させて頂きます。 ByteBufferやIntBuffer等のBufferクラスは、文字通りデータバッファを操作するクラスです。 getメソッドやputメソッド等でバッファの内容を読み書きすることができます。 そして、このバッファの実体は配列オブジェクトに対応しています。 これは補助配列と呼ばれています。 補助配列はarrayメソッドで取得できます。 補助配列はバッファの実体に対応しているため、補助配列を通してバッファの内容を読み書きすることが可能となります。 一方、ByteBufferのasIntBufferメソッドで元のByteBufferに対応するIntBufferを生成することができますが、生成されたIntBufferは実はByteBufferへのビューに過ぎません。 つまり、元のByteBufferも生成されたIntBufferも同じバッファを参照しています。 そして、生成されたIntBufferは補助配列を持ちません。 何故なら、このバッファに対する補助配列は元のByteBufferが提供するbyte[]型の配列しか存在しないためです。 そして、arrayメソッドは補助配列が利用できない時、UnsupportedOperationExceptionの例外を発生します。 このことは、下記に説明されています。 http://docs.oracle.com/javase/jp/8/api/java/nio/ByteBuffer.html#array-- 以上が、元のコードでエラーが発生する理由になります。 ご参考になれば幸いです。

その他の回答 (3)

  • yossy_kt
  • ベストアンサー率50% (103/203)
回答No.3

申し訳ありません、元のソースコードをきちんと確認していませんでした。 確かに仰る通り、先のコードはあまり意味がありませんね。 すみませんでした。 解答例のソースコードは意味のあるコードには見えませんでしたが、例えばビッグエンディアンとリトルエンディアンにおけるデータ格納方法の違いを知りたい場合、次のようなコードで確認できると思います。 public static void main(String[] args) { ByteBuffer bigBuffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); ByteBuffer litBuffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); int n = 0x01020304; bigBuffer.asIntBuffer().put(n); litBuffer.asIntBuffer().put(n); for (byte b : bigBuffer.array()) System.out.print(b + " "); System.out.println(""); for (byte b : litBytes.array()) System.out.print(b + " "); System.out.println(""); } このコードの実行結果から分かる通り、0x01020304(=16909060) のような値を格納すると、 ビッグエンディアン => 01 02 03 04 リトルエンディアン => 04 03 02 01 のように格納されます。 ちなみに、 int配列 {1, 2, 3, 4} は ビッグエンディアン {00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04} リトルエンディアン {01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00} となります。 ちょっとご質問の趣旨とずれてしまったかも知れませんが、ご参考になれば幸いです。

bakabon_xx
質問者

補足

yossy_kt さん 親切、明快な回答有難うございます。 貴方の回答の通り、ビッグエンディアンとリトルエンディアンでバイトの順序が 違うことを、確認しようとしましたが、練習問題の回答をベースにした改良では旨く行かないようです。 その後、コードを全く改良して、ビッグエンディアンとリトルエンディアンでバイトの順序が 逆になるコードを作成しました。 まあ、いわば間違っているかも知れない練習問題のお陰で、多少エンディアンについて理解が 深まった感じです(しかし、最初のエラーについては、未だ理解できていません)。 よって貴方に教えて頂いた『エラーの対策コード』についも、理解できていません。 もし出来れば、そのコードの説明をして頂ければ、有り難いです。 そのた: 私は、音声usbデーターの取込みを行なっていますが、libusb-win/wrapperではブロック抜けが 発生しますが、usb4javaでは、旨く行くようです。 これは、デバイスドライバーlibusb0.1とlibusb1.0の違いによるそうです。 つまり、前者はAsync伝送をサポートしておらず、後者はそれをサポートしているそうです。 その時、リトルエンディアンを使用しています。 以上

  • yossy_kt
  • ベストアンサー率50% (103/203)
回答No.2

説明が不足しているようでしたら、申し訳ありません。 下記のように変更してみてはいかがでしょうか? // ビックエンディアン ByteOrder order = ByteOrder.BIG_ENDIAN; ByteBuffer tmpBuffer = byteBuffer.order(order); // int[] ints = tmpBuffer.asIntBuffer().array(); IntBuffer iBuffer = tmpBuffer.asIntBuffer(); int[] ints = new int[iBuffer.limit()]; iBuffer.get(ints); IntBuffer intBuffer = IntBuffer.wrap(ints); System.out.println("ビックエンディアンで実行"); printChunk(random, ints, intBuffer); long end = System.currentTimeMillis(); System.out.println(""); System.out.print("経過時間:"); System.out.println((end - start) + "msec\t"); // リトルエンディアン start = System.currentTimeMillis(); order = ByteOrder.LITTLE_ENDIAN; tmpBuffer = byteBuffer.order(order); // ints = tmpBuffer.asIntBuffer().array(); iBuffer = tmpBuffer.asIntBuffer(); ints = new int[iBuffer.limit()]; iBuffer.get(ints); intBuffer = IntBuffer.wrap(ints); System.out.println("リトルエンディアンで実行"); printChunk(random, ints, intBuffer); end = System.currentTimeMillis(); System.out.println(""); System.out.print("経過時間:"); System.out.println((end - start) + "msec\t");

  • yossy_kt
  • ベストアンサー率50% (103/203)
回答No.1

asIntBuffer() は元のバッファのビューを作成するだけなので、array() をサポートしていないのだと思います。 とりあえず、下記のようにすればエラーは発生しないと思います。 IntBuffer iBuffer = byteBuffer.asIntBuffer(); ints = new int[iBuffer.limit()]; iBuffer.get(ints); 目的にあってなかったら、すみませんが。

bakabon_xx
質問者

お礼

yossy_ktさま 毎度、お世話になります。 私が勘違いしたところがあり、失礼な質問を繰り返して御免なさい。 貴方の、最初の、ご回答で旨く動作いたしました。 この上で、ビッグエンディアン、リトルエンディアンに関しまして、新規に 質問いたしますので、出来ればご回答をお願いします。 このプログラムはput(r)で入力しました乱数データーをそのまま、表示している様に 思えます。 私は、このプログラムは入力」しましたバイトデーターをエンディアン変換しまして その結果を表示すると思っていましたが、単にそのまま表示している様です。 私が期待もの: 入力(1,2,3,4,5,6,7,8,)--->(1234, 5678) これはビッグエンディアンの場合です。 以上、宜しくお願いします。

bakabon_xx
質問者

補足

毎度、お世話になります。 私の、力不足のために旨く行きません。 私の今回の、質問は下記から引用したものです。 もし出来れば、この回答のエラーを解消する方法をお教え頂けないで しょうか? TECHSCORE NewIO 2章 実習課題2 http://www.techscore.com/tech/Java/JavaSE/NIO/answer/2-2/ 以上、宜しくお願いします。

関連するQ&A

  • javaのOutOfMemoryErrorエラー

    毎度お世話になります。 void writeSync_Nword(DeviceHandle handle, int[] wordxxx)なるサブルーチンを 実行しますと、約500回に1回程度、下記の如く”OutOfMemoryError"エラーが発生します。 Q1)このエラーの対策につきまして、お教え頂けないでしょうか? Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Direct buffer memory at java.nio.Bits.reserveMemory(Bits.java:658) at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123) at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311) at org.usb4java.BufferUtils.allocateByteBuffer(BufferUtils.java:44) at FUNC_test.writeSync_Nword(FUNC_test.java:100) //============================================== public static void writeSync_Nword(DeviceHandle handle, int[] wordxxx){ byte[] data=int2ByteN(wordxxx); //little_endianでbyteに変換 ByteBuffer buffer = BufferUtils.allocateByteBuffer(data.length); //<---ここでエラー発生 buffer.put(data); IntBuffer transferred=BufferUtils.allocateIntBuffer(); int result=LibUsb.bulkTransfer(handle, EP_OUTcmd, buffer, transferred, TIMEOUT); if (result != LibUsb.SUCCESS){ throw new LibUsbException("Unable to execute writeSync_Nword", result); } } //=========================== public static byte[] int2ByteN(int word[]){ int n_word=word.length; ByteBuffer byteBuffer=ByteBuffer.allocate(Integer.SIZE/Byte.SIZE*n_word); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); for(int i=0; i<n_word; i++){ byteBuffer.putInt(word[i]); } return byteBuffer.array(); } 以上、宜しくお願いします。

    • ベストアンサー
    • Java
  • LITTLE_ENDIAN変換の結果の16進表示

    毎度、お世話になります。 下記のコードで、 bsはLITTLE_ENDIAN変換を行い、十進数表示で、67305985と表示されます。 これを、0x04030201とprint_outするコードをお教えください (1度intに変換しまして、そのintの内容を16進表示としたいと思います)。 byte[] bs = {0x01,0x2, 0x3, 0x4};  //lsd...Msd 0x04030201 ByteBuffer buffer = ByteBuffer.wrap(bs); buffer.order(ByteOrder.LITTLE_ENDIAN); System.out.println(buffer.getInt()); 以上、宜しくお願いします。

    • ベストアンサー
    • Java
  • Javaでのエンディアン変換

    こんばんは☆ Javaでのエンディアン変換をご教授ください。 ファイルを読み込み、ソケット通信でサーバへデータ送信しています。 リトルエンディアンで送らなければいけないのですが、 Javaはプラットフォーム問わずにビッグエンディアンでメモリに格納するとありました。 そこで、バイトオーダーをしようと思い、 stirlingというバイナリエディタでバイナリファイルを作成して以下の2点で試しました。 <バイナリファイル構造体> struct stest { LONG l1; LONG l2; LONG l3; LONG l4; }; <バイナリデータ(数値)> 1234 (010000020000030000040000)←バイナリエディタで見たとき <テスト1結果> ・・・new InputStreamReader(in, "UnicodeLittle"); >1000200030004000 <テスト2結果> ByteBuffer buffer = ByteBuffer.wrap(bt); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.get(); >1000200030004000 これはリトルエンディアンなのでしょうか? どちらも、 Javaで読み込み時にエンディアン指定しない時と出力結果に違いがありませんでした。 なぜでしょうか? ちなみに、データ型を意識せずに変換したいです。 色々と調べたのですが、良く分かりません。 どなたかご教授お願いいたしますm(_ _)m

    • ベストアンサー
    • Java
  • javaの超初心者です。ご教授いただけたら幸いです。

    javaの超初心者です。ご教授いただけたら幸いです。 ある書籍を元にやっているのですが、演習に答えがなく、わからないためその問題をお願い致します。 2桁の整数値(10~99)を当てさせる数当てゲームを作成せよ。という問題です。 下記は少しやってみました。 import java.util.Random; import java.util.Scanner; class Kazuate99 { public static void main(String[] args) { Random rand = new Random(); Scanner stdIn = new Scanner(System.in);    int no = rand.nextInt(); ← ここがたぶん違う System.out.println("数当てゲーム開始!!"); System.out.println("10~99の数を当てて下さい。"); int x; // プレーヤが入力した数 do { System.out.print("いくつかな : "); x = stdIn.nextInt(); if (x > no) System.out.println("もっと小さな数だよ。"); else if (x < no) System.out.println("もっと大きな数だよ。"); } while (x != no ); System.out.println("正解です。"); } } 宜しくお願い致します。

    • ベストアンサー
    • Java
  • javaのエラーの原因

    javaをテキストを使い独学しているのですが、演習問題でコンパイルに失敗する原因がわからず、回答もついていないので困っています 助けてください 問題文:-1.0以上1.0未満の実数地をランダムに生成して表示。実数地の乱数の生成にはnextDouble()を使うこと。 import java.util.Random; class Ran { public static void main(String[] args) { Random rand =new Random(); double x = rand.nextDouble(2); System.out.println(1-x); } } と記述したところ エラー 1 個 C:\MeikaiJava\Chap02>javac Ran.java Ran.java:8: nextDouble() (java.util.Random 内) を (int) に適用できません double x = rand.nextDouble(2); ^ と表示されます どこで失敗しているのでしょうか?

  • javaに関しての質問です (エラー)

    最近javaの勉強を始めたばかりの者です とある動画をみながら勉強をしていたのですが なぜかエラーが出てしまいます。 エラーの内容は... エラー:この文に制御が移ることはありません     if( c== 13){ エラー:return文が指定されていません この二つです、もし解決方法がわかる方がいましたらぜひ教えてくれるとうれしいです 下がソースコードになります。 public class part01 { static String name = "すけさん"; static int lv = 30; public static void main( String[] args )throws java.io.IOException { putzyosyou(); // 序章を表示 putcommnd(); if(lv<40){ putgameover(); }else{ putgamecrear(); } } public static void putzyosyou() { System.out.println("魔王が世界を滅ぼそうとしている。"); System.out.println(name + "はレベルが" + lv + "のツワモノです"); } public static void putcommnd()throws java.io.IOException { System.out.println("1.魔王を倒しに行く"); System.out.println("2.修行する"); System.out.println("3.だれかに頼る"); System.out.println("4.そんなことよりも寝よう"); int c = inputcommnd(); if( c== '1' ){ System.out.println("魔王が現れた!!"); }else if( c== '2' ){ lv += 2; System.out.println ("レベルが"+ lv + "になった!!"); putcommnd(); } } public static int inputcommnd()throws java.io.IOException { int c = System.in.read(); if( c== 10){ return( inputcommnd() ); if( c== 13){ return( inputcommnd() ); } return( c ); } } public static void putgameover() { System.out.println(name + "は負けました。"); System.out.println("GAME OVER"); } public static void putgamecrear() { String str = name + "は魔王を倒しました。"; put( str ); if(lv>120){ System.out.println("レベル" + lv + "なので魔王ゴミでした"); }else if(lv>80){ System.out.println("レベル" + lv + "なので余裕でした"); }else if(lv>50){ System.out.println("レベル" + lv + "なので倒せました"); }else{ System.out.println("レベル" + lv + "なので苦戦しました"); } System.out.println("GAME CREAR"); } static void put( String str ) { System.out.println( str ); } }

    • ベストアンサー
    • Java
  • javaについて

    以下のようにキーボードから入力していくプログラムを試行しているのですが、エラーが出てくるので行き詰まっています。 理想的にはキーボードに”あいう”エンター”えおか”エンターと打ち込んだら str[0]=あいう str[1]=えおか と表示させていきたいのですが、よろしくお願いします。 import java.io.*; import java.lang.*; import java.net.*; import java.awt.*; class gugu2 { public static void main(String[] args) throws IOException { int i=0; while(i<2){ System.out.println("キーワード入力"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); char str[] = input.toCharArray(); System.out.println("キーワードは" + str[]); i=i+1; } for(i=0;i<2;i++){ System.out.println(str[]); } } } これがエラー表示です。 gugu2.java:17: '.class' がありません。 System.out.println("キーワードは" + str[]); ^ gugu2.java:21: '.class' がありません。 System.out.println(str[]); ^ エラー 2 個

    • ベストアンサー
    • Java
  • JAVAの質問です。

    JAVAの質問です。 javaでスロットを作りたいのですが…。 3行3列で縦と横同じ数字の場合”おめでとう”と表示されるプログラムを作りたいのですがわからないです。 助けてください(>_<) public class surotto { public static void main(String args[]) { int hako[][]; int i,j; hako = new int[3][3]; System.out.println("スロットスタート。"); for(i=; i<3; i++){ for(j=0; j<3; j++){ hako[i][j] = (int)(Math.random()*10); } } for(i=0; i<3; i++){ for(j=0;j<3;j++){ System.out.println([i][j]); } System.out.println("\r\n"); } for(i=0; i<3 ; i++){ if((hako[i][0] == hako[i][1]) && (hako[i][1] == hako[i][2])){ System.out.println("横がそろいました、おめでとう\n"); } } for(j=0; j<3 ; j++){ if((hako[0][j] == hako[1][j]) && (hako[1][j] == hako[2][j])){ System.out.println("縦がそろいました、おめでとう\n"); } }

    • ベストアンサー
    • Java
  • javaのプログラム

    int型の配列の各要素に1~10の乱数を代入し、各要素の値を縦向きの*のグラフで表示するプログラムを作っているのですが、結果がランダムででるので、自分の書いたプログラムが正しいのかわかりません。ソースを載せますので合っているのか間違っているか教えて下さい。もし間違っているならどこが間違いなのか教えていただけると嬉しいです。よろしくお願いします。 ●ソース import java.util.Random; import java.util.Scanner; class Graph { public static void main(String[] args){ Random rand = new Random(); Scanner stdIn = new Scanner(System.in); System.out.print("要素数:"); int n = stdIn.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = 1 + rand.nextInt(10); for (int i = 1; i <= 10; i++){ for (int j = 0; j < n; j++) if (a[j] <= i) System.out.print("* "); else System.out.print(" "); System.out.println(); } } } ●実行例 要素数:12 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

    • ベストアンサー
    • Java
  • javaじゃんけんゲーの質問

    このjavaじゃんけんゲームで 0を押すまでじゃんけんが続いて0押したら終了して、終了と表示して、じゃんけんの勝敗が表示されるように作りたいんですけどどうしたらいいですか?教えてください import java.io.*; class kadai6 { public static void main(String args[]) throws IOException { System.out.println("これは、じゃんけんゲームです。"); System.out.println("あなたの手を入力して下さい。(1:グー、2:チョキ、3:パー、0:終了)さぁどれにしますか?"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int res =Integer.parseInt(str); switch(res){ case 1: System.out.println("あなたの手はグーです。"); break; case 2: System.out.println("あなたの手はチョキです。"); break; case 3: System.out.println("あなたの手はパーです。"); break; default: System.out.println("あなたの入力した値はエラーです。1~3の値を入力してください。"); System.exit(1); break; } int comp = (int)(Math.random()*3) + 1; switch (comp){ case 1: System.out.println("コンピュータの手はグーです。"); break; case 2: System.out.println("コンピュータの手はチョキです。"); break; case 3: System.out.println("コンピュータの手はパーです。"); break; default: System.out.println ("エラーです。"); break; } switch (res -comp) { case -2: System.out.println("コンピュータの勝ちです。"); break; case -1: System.out.println ("あなたの勝ちです。"); break; case 0: System.out.println ("あいこです。"); break; case 1: System.out.println ("コンピュータの勝ちです。"); break; case 2: System.out.println("あなたの勝ちです。"); break; default: System.out.println ("エラーです。"); break; } } }

専門家に質問してみよう